This commit is contained in:
Peter Maquiran
2022-03-03 22:57:33 +01:00
parent 3a81e6df4d
commit f5880fec2a
15 changed files with 877 additions and 801 deletions
+114 -129
View File
@@ -1,5 +1,6 @@
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
@@ -15,156 +16,140 @@ export class ChatStorageService {
* @description delete message in the DB. get all messages, delete then corresponding message and update the store
* @param id message ID
*/
private deleteMessageFromDb(messageId, roomId) {
this.storage.get('chatmsg' + roomId).then((messages: any = []) => {
async deleteMessageFromDb(messageId, roomId) {
if (environment.chatOffline) {
await this.storage.get('chatmsg' + roomId).then(async(messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
messages.forEach((message, index) => {
await messages.forEach( async (message, index) => {
if(message._id == messageId) {
messages.splice(index, 1)
}
})
this.storage.set('chatmsg' + roomId, messages).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
});
})
}
}
async updateMessageDB(ChatMessage, roomId, identificator) {
if (environment.chatOffline) {
await this.storage.get('chatmsg' + roomId).then(async(messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
let index;
const find = messages.find((message, _index)=> {
if(message?.localReference == ChatMessage?.localReference ||
message?._id == ChatMessage?._id) {
index = _index
return true
}
return false
})
if(find) {
messages[index] = Object.assign(messages[index], ChatMessage)
await this.storage.set('chatmsg' + roomId, messages)
} else {
console.log('failed to update', identificator, ':',ChatMessage)
}
})
}
}
getMsgFromDB() {
async updateChat(history, roomId, identificator = '_id') {
if (environment.chatOffline) {
await this.storage.get('chatmsg' + roomId).then(async(messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
/* this.storage.get('chatmsg' + this.id).then((message) => {
console.log('ALL MESSAGE WEB', message)
message.forEach(message => {
if (message.file) {
if (message.file.guid) {
this.storage.get(message.file.guid).then((image) => {
//console.log('IMAGE FROM STORAGE', image)
message.file.image_url = image
});
}
}
let mmessage = this.fix_updatedAt(message)
console.log('FROM DB WEB', mmessage)
const wewMessage = new MessageService(this.storage)
wewMessage.setData(mmessage)
this.messages.push(wewMessage)
console.log('loadHistory 222', this.messages)
});
}) */
}
history.forEach( async(ChatMessage)=>{
let index;
const find = messages.find((message, _index)=> {
if(message[identificator]) {
if(message[identificator] == ChatMessage[identificator]) {
index = _index
return true
}
}
return false
})
if(find) {
messages[index] = Object.assign(messages[index], ChatMessage)
// if(messages[index].msg.includes('***********')) {
// console.log('storage update')
// console.log(JSON.stringify(messages[index]))
// console.log(JSON.stringify(ChatMessage))
// }
await this.storage.set('chatmsg' + roomId, messages)
} else {
console.log('failed to update', identificator)
}
})
async transformData(res) {
// this.mgsArray = [];
// res.forEach(async element => {
// if (element.file) {
// if (element.file.guid) {
// await this.storage.get(element.file.guid).then((image) => {
// let chatmsg = {
// _id: element._id,
// attachments: element.attachments,
// channels: element.channels,
// file: {
// guid: element.file.guid,
// image_url: image,
// type: element.file.type
// },
// mentions: element.mentions,
// msg: element.msg,
// rid: element.rid,
// ts: element.ts,
// u: element.u,
// _updatedAt: element._updatedAt,
// }
// this.mgsArray.push(chatmsg);
// })
// } else {
// let chatmsg = {
// _id: element._id,
// attachments: element.attachments,
// channels: element.channels,
// file: element.file,
// mentions: element.mentions,
// msg: element.msg,
// rid: element.rid,
// ts: element.ts,
// u: element.u,
// _updatedAt: element._updatedAt,
// }
// this.mgsArray.push(chatmsg)
// }
// } else {
// let chatmsg = {
// _id: element._id,
// attachments: element.attachments,
// channels: element.channels,
// mentions: element.mentions,
// msg: element.msg,
// rid: element.rid,
// ts: element.ts,
// u: element.u,
// _updatedAt: element._updatedAt,
// }
// this.mgsArray.push(chatmsg)
// }
// });
// await this.storage.remove('chatmsg').then(() => {
// console.log('MSG REMOVE FROM STORAGE')
// });
// await this.storage.set('chatmsg', this.mgsArray).then((value) => {
// console.log('MSG SAVED ON STORAGE', value)
// });
})
}
}
async addMessageDB(ChatMessage, roomId) {
if (environment.chatOffline) {
await this.storage.get('chatmsg' + roomId).then(async(messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
getMsgFromDBMobile() {
// console.log('ALL MSG DBBB', this.id)
// this.sqlservice.getAllChatMSG(this.id).then((msg: any = []) => {
// let ad = [];
// ad = msg
// console.log('ALL MSG DBBB', ad.length)
// msg.map(element => {
// console.log('CHANNEL ELEMENT', element)
// let msgChat = {
// _id: element.Id,
// attachments: this.isJson(element.Attachments),
// channels: this.isJson(element.Channels),
// file: {
// guid: this.isJson(element.File).guid,
// image_url: this.isJson(element.image_url),
// type: this.isJson(element.File).type
// },
// mentions: this.isJson(element.Mentions),
// msg: element.Msg,
// rid: element.Rid,
// ts: element.Ts,
// u: this.isJson(element.U),
// _updatedAt: this.isJson(element.UpdatedAt),
// }
// let mmessage = this.fix_updatedAt(msgChat)
// console.log('FROM DB WEB', mmessage)
// const wewMessage = new MessageService(this.storage)
// wewMessage.setData(mmessage)
// this.messages.push(wewMessage)
// console.log('loadHistory 222', this.messages)
// });
// });
if(!ChatMessage._id && environment.chatOffline) {
delete ChatMessage.temporaryData
messages.push(ChatMessage)
await this.storage.set('chatmsg' + roomId, messages)
console.log('add to DB', ChatMessage)
} else {
const find = messages.find((message)=> {
return message._id == ChatMessage._id
})
if(!find) {
delete ChatMessage.temporaryData
messages.push(ChatMessage)
await this.storage.set('chatmsg' + roomId, messages)
console.log('add to DB', ChatMessage)
}
}
})
}
}
}
+105 -48
View File
@@ -7,6 +7,8 @@ import { NfService } from 'src/app/services/chat/nf.service'
import { WsChatService } from 'src/app/services/chat/ws-chat.service';
import { environment } from 'src/environments/environment';
import { showDateDuration } from 'src/plugin/showDateDuration';
import { ChatStorageService } from './chat-storage.service'
@Injectable({
providedIn: 'root'
})
@@ -26,7 +28,7 @@ export class MessageService {
}
t = ''
_id =''
_id = ''
_updatedAt
file
attachments
@@ -44,13 +46,16 @@ export class MessageService {
viewed = []
received = []
messageSend = false
constructor(private storage: Storage,
private NfService: NfService,
private WsChatService: WsChatService) {
private WsChatService: WsChatService,
private ChatStorageService: ChatStorageService) {
}
setData({customFields = {}, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData, localReference}:Message) {
this.customFields = customFields
setData({customFields = {}, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData, localReference , viewed = [], received = []}:Message) {
this.channels = channels || []
this.mentions = mentions || []
this.msg = msg || ""
@@ -65,9 +70,23 @@ export class MessageService {
this.temporaryData = temporaryData
this.localReference = localReference || null
if(this.msg.includes('***********')) {
console.log('-=-=--=-=-=',JSON.stringify(viewed), JSON.stringify(this.viewed))
}
this.viewed = [...new Set([...viewed,...this.viewed])];
this.received = [...new Set([...received,...this.received])];
if(this.msg.includes('***********')) {
console.log('-=-=--=-=-=',JSON.stringify(viewed), JSON.stringify(this.viewed))
}
if(!this.ts) {
this.offline = true
this.messageSend = false
} else {
this.messageSend = true
this.offline = false
}
@@ -79,10 +98,6 @@ export class MessageService {
}
}
// if(typeof(this.file?.type)) {
// this.hasFile = true
// }
if(this.hasFile) {
this.getFileFromDb()
if(this.file.type != 'application/webtrix') {
@@ -90,7 +105,6 @@ export class MessageService {
}
}
this.calDateDuration()
}
@@ -121,10 +135,11 @@ export class MessageService {
if(!this.hasFile) {
this.WsChatService.send({roomId:this.rid, msg:this.msg, localReference: this.localReference}).then(({message, requestId}) => {
let ChatMessage = message.result
this.messageSend = true
this.redefinedMessage(ChatMessage)
if (environment.chatOffline) {
// this.redefinedMessage(ChatMessage)
this.offline = false
}
@@ -151,17 +166,21 @@ export class MessageService {
this.WsChatService.send({roomId:this.rid, msg: this.msg, attachments: this.attachments, file: this.file, localReference: this.localReference}).then(({message, requestId}) => {
console.log('message', message)
let ChatMessage = message.result
this.messageSend = true
this.redefinedMessage(ChatMessage)
if (environment.chatOffline) {
// this.redefinedMessage(ChatMessage)
this.offline = false
}
return new Promise((resolve, reject)=>{
resolve(ChatMessage)
})
})
} else if(this.WsChatService.isLogin == false) {
@@ -185,12 +204,39 @@ export class MessageService {
}
redefinedMessage(ChatMessage) {
async redefinedMessage(ChatMessage , update = true) {
ChatMessage = this.NfService.fix_updatedAt(ChatMessage)
let reference
if(this._id) {
reference = '_id'
} else {
reference = 'localReference'
}
const message = this.getChatObj()
// const viewed = [...new Set([...ChatMessage.viewed,...this.viewed])];
// const received = [...new Set([...ChatMessage.received,...this.received])];
// if(ChatMessage.msg.includes('***********')) {
// console.log('redefinedMessage')
// console.log(JSON.stringify(ChatMessage))
// console.log(JSON.stringify(message))
// console.log(JSON.stringify(Object.assign(message, ChatMessage)))
// }
ChatMessage = Object.assign(message, ChatMessage)
if(update) {
await this.ChatStorageService.updateMessageDB(ChatMessage, this.rid, reference)
}
this.setData(ChatMessage)
}
async downloadFileMsg() {
const result = await this.NfService.beforeSendAttachment(this)
if(result) {
@@ -207,43 +253,54 @@ export class MessageService {
return this.u.username != SessionStore.user.RochetChatUser
}
receptorReceive() {
if(this.messageReceptor()) {
let newMessage = {
rid: this._id,
msg: this.msg,
attachments: this.attachments,
file: this.file,
localReference: this.localReference,
viewed: this.viewed.push('123'),
received: this.viewed.push('123'),
}
this.WsChatService.updateMessage(newMessage).then(()=>{
console.log('newMessage', newMessage)
})
}
async delete() {
await this.ChatStorageService.deleteMessageFromDb(this._id, this.rid)
}
receptorView() {
if(this.messageReceptor()) {
let newMessage = {
rid: this._id,
msg: this.msg,
attachments: this.attachments,
file: this.file,
localReference: this.localReference,
viewed: this.viewed.push('123'),
received: this.viewed.push('123'),
}
this.WsChatService.updateMessage(newMessage).then(()=>{
console.log('newMessage', newMessage)
})
isSenderIsNotMe(ChatMessage) {
return SessionStore.user.RochetChatUser != ChatMessage.u.username
}
messageOwnerById(id) {
return SessionStore.user.RochetChatUser != this.u.username
}
private getChatObj() {
return {
channels: this.channels,
mentions: this.mentions,
msg: this.msg,
rid: this.rid,
ts: this.ts,
u: this.u,
_id: this._id,
_updatedAt: this._updatedAt,
messageSend: this.messageSend,
offline: this.offline,
viewed: this.viewed,
received: this.received,
localReference: this.localReference
}
}
async addMessageDB() {
const message = this.getChatObj()
await this.ChatStorageService.addMessageDB(message, this.rid)
}
async save() {
const message = this.getChatObj()
let reference
if(this._id) {
reference = '_id'
} else {
reference = 'localReference'
}
await this.ChatStorageService.updateMessageDB(message, this.rid, reference)
}
}
+218 -190
View File
@@ -16,6 +16,7 @@ import { environment } from 'src/environments/environment';
import { ChatService } from 'src/app/services/chat.service';
import { NfService } from 'src/app/services/chat/nf.service';
import { v4 as uuidv4 } from 'uuid'
import { ChatStorageService } from './chat-storage.service'
@Injectable({
providedIn: 'root'
@@ -32,6 +33,7 @@ export class RoomService {
name = ''
_updatedAt = {}
hasLoadHistory = false
restoreFromOffline = false
duration = ''
isTyping = false
otherUserType = false
@@ -39,10 +41,10 @@ export class RoomService {
message = ''
lastMessageTxt = ''
userThatIsTyping = ''
private ToastService = ToastsService
mgsArray = [];
messagesLocalReference = []
members = []
u
scrollDown = () => { }
@@ -66,21 +68,60 @@ export class RoomService {
private NativeNotificationService: NativeNotificationService,
private sortService: SortService,
private chatService: ChatService,
private NfService: NfService
private NfService: NfService,
private ChatStorageService: ChatStorageService
) {
this.NativeNotificationService.askForPermission()
this.restoreMessageFromDB()
this.WsChatService.getUserStatus((d) => {
const userId = d.fields.args[0][0]
if(this.members?.map) {
const membersIds = this.members.map((user)=> user._id)
if(membersIds.includes(userId)) {
this.messages.forEach((message, index) => {
if(!message.messageOwnerById(userId)) {
if(!this.messages[index]?.received?.includes(userId)) {
if(this.messages[index]._id) {
try {
this.messages[index].received.push(userId)
} catch(e) {
this.messages[index].received = [userId]
}
this.messages[index].save()
}
}
}
})
}
}
})
}
setData({ customFields = {}, id, name, t, lastMessage = new MessageService(this.storage, this.NfService, this.WsChatService), _updatedAt }) {
setData({members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService), _updatedAt }) {
this.customFields = customFields
this.id = id
this.name = name
this.t = t
this.lastMessage = lastMessage
this._updatedAt = _updatedAt
this.u = u
this.members = members
this.calDateDuration()
this.restoreMessageFromDB()
}
@@ -89,19 +130,26 @@ export class RoomService {
return SessionStore.user.RochetChatUser != ChatMessage.u.username
}
senderId(ChatMessage) {
return ChatMessage.u._id
}
receiveMessage() {
this.WsChatService.updateRoomEventss(
this.id,
"stream-room-messages",
(_ChatMessage) => {
async (_ChatMessage) => {
console.log('recivemessage', _ChatMessage)
let ChatMessage = _ChatMessage.fields.args[0]
ChatMessage = this.fix_updatedAt(ChatMessage)
if(!this.messagesLocalReference.includes(ChatMessage.localReference)) {
const message = this.prepareMessage(ChatMessage)
const message = await this.prepareMessage({message: ChatMessage, save: true})
message.messageSend = true
this.lastMessage = message
this.calDateDuration(ChatMessage._updatedAt)
@@ -114,154 +162,63 @@ export class RoomService {
message: message.msg,
title: this.name
});
}
this.addMessageDB(ChatMessage)
message.addMessageDB()
setTimeout(()=>{
this.scrollDown()
}, 50)
}
} else {
this.messages.forEach((message, index)=> {
if(message.localReference == ChatMessage.localReference) {
const membersIds = this.members.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.WsChatService.receiveStreamNotifyRoom((message) => {
if(message.fields.eventName == this.id+'/'+'typing') {
this.userThatIsTyping = this.usernameToDisplayName(message.fields.args[0])
console.log(this.userThatIsTyping, 'this.userThatIsTyping')
this.isTyping = message.fields.args[1]
this.otherUserType = message.fields.args[1]
const args = message.fields.args
if (typeof args[0] != 'object') {
this.userThatIsTyping = this.usernameToDisplayName(args[0])
console.log(this.userThatIsTyping, 'this.userThatIsTyping')
this.isTyping = args[1]
this.otherUserType = args[1]
this.readAllMessage()
} else {
this.readAllMessage()
}
} else if (message.fields.eventName == this.id+'/'+'deleteMessage') {}
})
}
async addMessageDB(ChatMessage) {
if (environment.chatOffline) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
if(!ChatMessage._id && environment.chatOffline) {
delete ChatMessage.temporaryData
messages.push(ChatMessage)
this.storage.set('chatmsg' + this.id, messages)
} else {
const find = messages.find((message)=> {
return message._id == ChatMessage._id
})
if(!find) {
delete ChatMessage.temporaryData
messages.push(ChatMessage)
this.storage.set('chatmsg' + this.id, messages)
}
}
})
}
}
async updateMessageDB(ChatMessage, localReference) {
if (environment.chatOffline) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
let index;
const find = messages.find((message, _index)=> {
if(message.localReference) {
if(message?.localReference == ChatMessage?.localReference) {
index = _index
return true
}
}
return false
})
if(find) {
messages[index] = ChatMessage
this.storage.set('chatmsg' + this.id, messages)
}
})
}
}
async updateViewedMessage(id, userId) {
if (environment.chatOffline) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
let index;
const find = messages.find((message, _index)=> {
if(message._id == id) {
index = _index
return true
}
return false
})
if(find) {
if(!messages[index].hasOwnProperty('viewed') || !Array.isArray(messages[index].viewed)) {
messages.viewed = []
}
messages.viewed.push(userId)
this.storage.set('chatmsg' + this.id, messages)
}
})
}
}
/**
* @description delete message in the DB. get all messages, delete then corresponding message and update the store
* @param id message ID
*/
private deleteMessageFromDb(id) {
if (environment.chatOffline) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
messages.forEach((message, index) => {
if(message._id == id) {
messages.splice(index, 1)
}
})
this.storage.set('chatmsg' + this.id, messages).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
});
})
}
}
async receiveMessageDelete() {
@@ -286,9 +243,10 @@ export class RoomService {
deleteMessage(id) {
this.messages.forEach((message, index) => {
if(message._id == id) {
this.messages.splice(index, 1)
message.delete()
this.deleteMessageFromDb(id)
//Get previous last message from room
const previousLastMessage = this.messages.slice(-1)[0];
@@ -298,6 +256,7 @@ export class RoomService {
}
})
}
@@ -314,24 +273,17 @@ export class RoomService {
attachments,
file,
temporaryData,
localReference,
viewed: [],
received: []
localReference
}
const message: MessageService = await this.prepareMessage({message:offlineChatMessage, save: environment.chatOffline})
const message: MessageService = this.prepareMessage(offlineChatMessage, environment.chatOffline)
/**
* @description redefine message offline data "offlineChatMessage" with live ChatMessage
*/
message.send().then((ChatMessage) => {
this.updateMessageDB(ChatMessage, localReference)
})
this.messagesLocalReference.push(localReference)
await message.addMessageDB()
message.send()
if (environment.chatOffline) {
this.messagesLocalReference.push(localReference)
this.addMessageDB(offlineChatMessage)
setTimeout(() => {
this.scrollDown()
@@ -346,25 +298,6 @@ export class RoomService {
}
/**
*
* @param message
* @param ChatMessage
* @description when creating message we use offline data, then we need redefined with live data
*/
redefinedMessage (message: MessageService, ChatMessage) {
ChatMessage = this.fix_updatedAt(ChatMessage)
message.setData(ChatMessage)
if( new Date(this.lastMessage._updatedAt).getTime() < new Date(message._updatedAt).getTime()) {
this.lastMessage = message
this.calDateDuration(message._updatedAt)
}
this.sortRoomList()
}
sendTyping(text:string = this.message) {
@@ -387,6 +320,10 @@ export class RoomService {
this.typingWatch()
}
sendFalseTypingReadMessage() {
this.WsChatService.sendStreamNotifyRoom(this.id, SessionStore.user.RochetChatUser, 'typing', {})
this.setTypingOff()
}
private typingWatch() {
setTimeout(()=>{
@@ -440,19 +377,25 @@ export class RoomService {
messages = []
}
// console.log('offline messages', messages)
await messages.forEach( async (ChatMessage, index) => {
const wewMessage = this.prepareMessage(ChatMessage, false)
// if(ChatMessage.msg.includes('***********')) {
// console.log('restore ========')
// console.log(JSON.stringify(ChatMessage))
// }
const wewMessage = await this.prepareMessage({message:ChatMessage, save: false})
if(wewMessage.offline == false) {
this.prepareMessage(ChatMessage)
} else {
const offlineMessage = this.prepareMessage(ChatMessage)
const offlineMessage = await this.prepareMessage({message:ChatMessage, save: true})
this.messagesLocalReference.push(offlineMessage.localReference)
offlineMessage.send().then((newChatMessage) => {
this.updateMessageDB(newChatMessage, ChatMessage.localReference)
})
// offlineMessage.send()
}
});
@@ -467,7 +410,7 @@ export class RoomService {
}
// runs onces only
async loadHistory({limit = 50, forceUpdate = false }) {
async loadHistory({limit = 10000000, forceUpdate = false }) {
if(forceUpdate == false) {
if (this.hasLoadHistory) {
@@ -475,15 +418,23 @@ export class RoomService {
}
}
if(this.restoreFromOffline == false) {
this.restoreFromOffline = true
await this.restoreMessageFromDB()
}
await this.WsChatService.loadHistory(this.id, limit).then( async (chatHistory:chatHistory) => {
await chatHistory.result.messages.reverse().forEach( async (message) => {
this.prepareMessage(message)
// this.messages = this.sortService.sortDate(this.messages, '_updatedAt')
// await this.prepareMessage({message})
})
// console.log('load history ',chatHistory)
await this.readMessage(chatHistory)
//await this.updateAllMessages()
this.storage.set('chatmsg' + this.id, chatHistory.result.messages)
})
@@ -494,6 +445,72 @@ export class RoomService {
this.hasLoadHistory = true
}
async readMessage(chatHistory) {
const firstUnread = chatHistory.result.firstUnread
let foundUnread = false
// if (chatHistory.result.unreadNotLoaded == 0) {
// const membersIds = this.members.map((user)=> user._id)
// this.messages.forEach((message, index) => {
// if(message.viewed.length == 0) {
// this.messages[index].viewed = membersIds
// }
// })
// } else {
// chatHistory.result.messages.forEach((message) => {
// console.log(message._id == firstUnread._id)
// if(message._id == firstUnread._id) {
// foundUnread = true
// console.log('found=============================')
// } else {
// console.log('message')
// }
// });
// }
}
async readAllMessage() {
const membersIds = this.members.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
}
}
})
this.updateAllMessages()
}
updateAllMessages () {
const newHistory = this.messages.map((message) => {
return {
channels: message.channels,
mentions: message.mentions,
msg: message.msg,
rid: message.rid,
ts: message.ts,
u: message.u,
_id: message._id,
_updatedAt: message._updatedAt,
messageSend: message.messageSend,
offline: message.offline,
viewed: message.viewed,
received: message.received
}
})
this.ChatStorageService.updateChat(newHistory, this.id)
}
/**
* @description find or create message
@@ -501,32 +518,40 @@ export class RoomService {
* @param save
* @returns
*/
prepareMessage(message, save = true): MessageService {
async prepareMessage({message, save = true, redefined = false}): Promise<MessageService> {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService)
wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory
if(!message._id && environment.chatOffline && save) {
if(!message?._id && environment.chatOffline && save) {
this.messages.push(wewMessage)
return wewMessage
}
const found = this.messages.find((MessageService) => {
let foundIndex;
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == message._id) {
if(this.hasLoadHistory) console.log(`${MessageService._id} == ${message._id}`)
foundIndex = index
return true
} else {
return false
}
})
if (save && !found) {
if (save || !found) {
this.messages.push(wewMessage)
return wewMessage
} else{
if(redefined) {
}
return this.messages[foundIndex]
}
return wewMessage
}
private calDateDuration(date = null) {
@@ -534,11 +559,10 @@ export class RoomService {
this._updatedAt = date || this._updatedAt
}
private fix_updatedAt(message) {
if (message.result) {
if (message?.result) {
message.result._updatedAt = message.result._updatedAt['$date']
} else if(message._updatedAt) {
} else if(message?._updatedAt) {
if(message._updatedAt.hasOwnProperty('$date')) {
message._updatedAt = message._updatedAt['$date']
}
@@ -546,7 +570,6 @@ export class RoomService {
return message
}
usernameToDisplayName(username) {
const firstName = capitalizeTxt(username.split('.')[0])
@@ -554,4 +577,9 @@ export class RoomService {
return firstName + ' ' + lastName
}
sendReadMessage() {
this.WsChatService.readMessage(this.id)
this.sendFalseTypingReadMessage()
}
}
@@ -14,6 +14,10 @@ import { SortService } from '../functions/sort.service';
import { chatUser } from 'src/app/models/chatMethod';
import { NfService } from 'src/app/services/chat/nf.service'
import { ChangeProfileService } from '../change-profile.service';
import { UserSession } from 'src/app/models/user.model';
import { AuthService } from '../auth.service';
import { ChatStorageService } from './chat-storage.service'
@Injectable({
providedIn: 'root'
})
@@ -33,6 +37,8 @@ export class WsChatMethodsService {
currentRoom: RoomService = null
users: chatUser[] = []
loggedUser: any;
constructor(
private WsChatService: WsChatService,
private storage: Storage,
@@ -43,8 +49,13 @@ export class WsChatMethodsService {
private ChatService: ChatService,
private NfService: NfService,
private changeProfileService: ChangeProfileService,
private chatService: ChatService,
private authService: AuthService,
private ChatStorageService: ChatStorageService
) {
this.loggedUser = authService.ValidatedUserChat['data'];
this.loadChat()
this.WsChatService.registerCallback({
@@ -79,39 +90,6 @@ export class WsChatMethodsService {
this.storage.remove('Rooms');
})
// this.WsChatService.registerCallback({
// type:'Onmessage',
// funx:(message) => {
// if(message.msg =='changed' && message.collection == "stream-room-messages") {
// if(message.fields.args[0].rid) {
// // new message
// const ChatMessage = message.fields.args[0]
// const messageId = ChatMessage.rid
// setTimeout(()=>{
// this.sortRoomList()
// }, 100)
// }
// } else if(message.msg =='changed' && message.collection == "stream-notify-room") {
// if(message.fields.eventName.includes('deleteMessage')) {
// // delete message
// const DeletedMessageId = message.fields.args[0]._id;
// setTimeout(()=>{
// this.sortRoomList()
// }, 100)
// } else if(message.fields.eventName.includes('typing')) {
// }
// }
// }
// })
}
private loadChat() {
@@ -144,7 +122,6 @@ export class WsChatMethodsService {
this.users = []
}
openRoom(roomId) {
if(this.currentRoom) {
@@ -161,7 +138,6 @@ export class WsChatMethodsService {
}
async restoreRooms() {
try {
@@ -183,14 +159,46 @@ export class WsChatMethodsService {
this.loadingWholeList = true
const rooms = await this.WsChatService.getRooms();
await this.storage.remove('Rooms');
await this.storage.set('Rooms', rooms);
console.log('rooms', rooms)
await rooms.result.update.forEach( async (roomData: room) => {
await this.prepareRoom(roomData);
console.log('rooms ============', rooms)
await rooms.result.update.forEach( async (roomData: room, index) => {
const roomId = this.getRoomId(roomData);
if(roomData.t == 'd') {
const res = await this.chatService.getMembers(roomId).toPromise();
const members = res['members'];
const users = members.filter(data => data.username != this.loggedUser.me.username);
rooms.result.update[index]['members'] = users
await this.prepareRoom(roomData);
} else {
if (roomData.t === 'p') {
const res = await this.chatService.getGroupMembers(roomId).toPromise()
const members = res['members'];
const users = members.filter(data => data.username != this.loggedUser.me.username);
rooms.result.update[index]['members'] = users
}
else {
const res = await this.chatService.getChannelMembers(roomId).toPromise()
const members = res['members'];
const users = members.filter(data => data.username != this.loggedUser.me.username);
rooms.result.update[index]['members'] = users
}
}
});
await this.storage.set('Rooms', rooms);
console.log(rooms.result.update, 'rooms.result.update')
this.sortRoomList()
this.loadingWholeList = false
}
@@ -247,6 +255,8 @@ export class WsChatMethodsService {
})
this.WsChatService.subStreamNotifyRoom(id, 'typing', false)
this.WsChatService.subStreamNotifyRoom(id, 'readMessage', false)
this.WsChatService.streamNotifyRoomDeleteMessage(id).then((subscription)=>{
//console.log('streamNotifyRoomDeleteMessage', subscription);
})
@@ -269,14 +279,16 @@ export class WsChatMethodsService {
name: this.getRoomName(roomData),
t: roomData.t,
lastMessage: this.getRoomLastMessage(roomData),
_updatedAt: new Date(roomData._updatedAt['$date'])
_updatedAt: new Date(roomData._updatedAt['$date']),
u : roomData.u || {},
members: roomData.members
}
let roomId = this.getRoomId(roomData)
// create room
if(!this.roomExist(roomId)) {
let room:RoomService = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService, this.WsChatService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService)
let room:RoomService = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService , this.ChatStorageService)
room.setData(setData)
room.receiveMessage()
room.getAllUsers = this.getUsers
@@ -300,7 +312,6 @@ export class WsChatMethodsService {
}
} else {
console.log('have!!!')
// in this case room is already present, therefor it will only be necessary,
// to redefine
@@ -336,16 +347,16 @@ export class WsChatMethodsService {
const username = d.fields.args[0][1]
const statusNum = d.fields.args[0][2]
const statusText = this.statusNumberToText(statusNum)
const user = this.getUserByName(username)
if(user) {
user.status = statusText
}
this.users.forEach((user, index) => {
if(user.username == username) {
this.users[index].status = statusText
}
})
})
}
getUserByName(username) {
@@ -460,9 +471,9 @@ export class WsChatMethodsService {
let _res = await this.ChatService.getAllUsers().toPromise()
let user = _res['users'].filter(data => data.username != SessionStore.user.RochetChatUser);
let users = _res['users'].filter(data => data.username != SessionStore.user.RochetChatUser);
user = user.sort((a,b) => {
users = users.sort((a,b) => {
if(a.name < b.name) {
return -1;
}
@@ -472,7 +483,11 @@ export class WsChatMethodsService {
return 0;
});
this.users = user
users.forEach((user, index) => {
// user[index].status = this.statusNumberToText(user[index].status)
})
this.users = users
}
getUserOfRoom(roomId){
+29 -4
View File
@@ -123,6 +123,30 @@ export class WsChatService {
});
}
readMessage(roomId) {
const requestId = uuidv4()
const message = {
"msg":"method",
"method":"readMessages",
"params": [roomId, []],
"id": requestId
}
this.ws.send({message, requestId})
return new Promise<Rooms>((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId) { // same request send
resolve(message)
return true
}
}})
});
}
getUserOfRoom(roomId) {
const requestId = uuidv4()
@@ -174,6 +198,8 @@ export class WsChatService {
}]
}
console.log('send message to rocketchat ', message)
this.ws.send({message, requestId});
return new Promise((resolve, reject) => {
@@ -285,7 +311,7 @@ export class WsChatService {
});
}
joinRoom(){}
joinRoom() {}
deleteMessage(msgId) {
const requestId = uuidv4();
@@ -369,7 +395,7 @@ export class WsChatService {
}
subStreamNotifyRoom(roomId : string , event: 'typing' | 'deleteMessage', param: any) {
subStreamNotifyRoom(roomId : string , event: 'typing' | 'deleteMessage' | 'readMessage', param: any) {
const requestId = uuidv4()
@@ -496,7 +522,7 @@ export class WsChatService {
}
updateRoomEventss(roomId, collection:string, funx: Function, ) {
updateRoomEventss(roomId, collection:string, funx: Function, ) {
this.ws.registerCallback({
type:'Onmessage',
@@ -515,7 +541,6 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) {
})
}
streamRoomMessages(roomId : string) {
const requestId = uuidv4()