change storage package to beast-rom

This commit is contained in:
Peter Maquiran
2022-03-10 23:08:29 +01:00
parent f3aabae9c7
commit c2b1a54a6e
18 changed files with 256 additions and 185 deletions
+1
View File
@@ -54,3 +54,4 @@ node_modules_
node_modules__ node_modules__
plugins_ plugins_
ios ios
src/plugin/beast-orm
+5
View File
@@ -6151,6 +6151,11 @@
"tweetnacl": "^0.14.3" "tweetnacl": "^0.14.3"
} }
}, },
"beast-orm": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/beast-orm/-/beast-orm-0.0.7.tgz",
"integrity": "sha512-Fd/v6aPWnMD9Hu0vInc2t0QMNN7qdyWZhqTinFyPsHbEoO2CXRaM+CeFZQN3rnmRIj8/OHmVGJZoejVI6R809w=="
},
"big-integer": { "big-integer": {
"version": "1.6.49", "version": "1.6.49",
"resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.49.tgz", "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.49.tgz",
+1
View File
@@ -97,6 +97,7 @@
"angular-cropperjs": "^0.1.5", "angular-cropperjs": "^0.1.5",
"angular-svg-icon": "^12.0.0", "angular-svg-icon": "^12.0.0",
"angular-tag-cloud-module": "^5.2.2", "angular-tag-cloud-module": "^5.2.2",
"beast-orm": "0.0.7",
"bootstrap": "^4.5.0", "bootstrap": "^4.5.0",
"build": "0.1.4", "build": "0.1.4",
"capacitor-voice-recorder": "^2.0.0", "capacitor-voice-recorder": "^2.0.0",
+1 -1
View File
@@ -12,7 +12,7 @@ import { SqliteService } from 'src/app/services/sqlite.service';
import { BackgroundService } from 'src/app/services/background.service'; import { BackgroundService } from 'src/app/services/background.service';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx'; import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
import { StorageService } from 'src/app/services/storage.service'; import { StorageService } from 'src/app/services/storage.service';
import { MessageModel } from './models/beast-orm'
const CUSTOM_DATE_FORMATS: NgxMatDateFormats = { const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
parse: { parse: {
@@ -120,7 +120,7 @@ export class ChatOptionsFeaturesPage implements OnInit {
} }
this.chatService.sendMessage(body).subscribe(res=> { this.chatService.sendMessage(body).subscribe(res=> {
console.log(res); // console.log(res);
},(error) => { },(error) => {
}); });
+45
View File
@@ -0,0 +1,45 @@
import { models } from 'beast-orm'
import { AESEncrypt } from '../services/aesencrypt.service'
const _AESEncrypt = new AESEncrypt()
export class MessageModel extends models.Model {
channels = models.IndDbJsonField()
mentions = models.IndDbJsonField()
msg = models.CharField()
rid = models.CharField()
ts = models.CharField()
u = models.IndDbJsonField()
_id = models.CharField({unique:true})
_updatedAt = models.CharField()
messageSend = models.BooleanField()
offline = models.BooleanField()
viewed = models.IndDbJsonField()
received = models.IndDbJsonField()
localReference = models.CharField({blank:true})
attachments = models.IndDbJsonField()
file = models.IndDbJsonField()
}
export class DeleteMessageModel extends models.Model {
messageId = models.IntegerField()
rid = models.CharField()
ts = models.CharField()
u = models.IndDbJsonField()
_id = models.CharField({unique:true})
receivedBy = models.IndDbJsonField()
}
models.register({
databaseName: 'chat-storage',
type: 'indexeddb',
version: 1,
models: [MessageModel, DeleteMessageModel]
})
+1
View File
@@ -67,6 +67,7 @@ interface FirstUnread {
export interface Message { export interface Message {
customFields:any; customFields:any;
_id: string; _id: string;
id: null | string;
rid: string; rid: string;
msg: string; msg: string;
ts: Ts; ts: Ts;
+45 -3
View File
@@ -1,4 +1,46 @@
export interface Message { export interface IncomingChatMessage {
author: string; msg: string;
message: string; collection: string;
id: string;
fields: {
args: {
_id: string;
rid: string;
localReference: string;
msg: string;
file?: any;
ts: {
$date: number;
};
u: {
_id: string;
username: string;
name: string;
};
_updatedAt: {
$date: number;
};
mentions: any[];
channels: any[];
} [];
} }
eventName: string;
};
export interface ChatMessageInterface {
_id: string;
rid: string;
localReference: string;
msg: string;
file?: any;
ts: number;
u: {
_id: string;
username: string;
name: string;
};
_updatedAt: number;
mentions: any[];
channels: any[];
};
-5
View File
@@ -20,7 +20,6 @@ import { NewGroupPage } from './new-group/new-group.page';
import { Storage } from '@ionic/storage'; import { Storage } from '@ionic/storage';
import { EditGroupPage } from 'src/app/shared/chat/edit-group/edit-group.page'; import { EditGroupPage } from 'src/app/shared/chat/edit-group/edit-group.page';
import * as Rx from "rxjs/Rx"; import * as Rx from "rxjs/Rx";
import { Message } from 'src/app/models/message.model';
import { Observable, Subject } from "rxjs/Rx"; import { Observable, Subject } from "rxjs/Rx";
import { NavigationStart, NavigationEnd, Router } from '@angular/router'; import { NavigationStart, NavigationEnd, Router } from '@angular/router';
import { EventPerson } from 'src/app/models/eventperson.model'; import { EventPerson } from 'src/app/models/eventperson.model';
@@ -143,10 +142,6 @@ export class ChatPage implements OnInit {
ngOnInit() { ngOnInit() {
console.log('Rooms INDIVIDUAIS',this.wsChatMethodsService._dm);
console.log(' ROOMS GROUP',this.wsChatMethodsService._group);
this.segment = "Contactos"; this.segment = "Contactos";
this.authService.userData$.subscribe((res: any) => { this.authService.userData$.subscribe((res: any) => {
@@ -418,8 +418,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.chatService.getMembers(this.roomId).subscribe(res => { this.chatService.getMembers(this.roomId).subscribe(res => {
this.members = res['members']; this.members = res['members'];
this.dmUsers = res['members'].filter(data => data.username != this.loggedUser.me.username) this.dmUsers = res['members'].filter(data => data.username != this.loggedUser.me.username)
console.log(res);
console.log(this.dmUsers);
this.showLoader = false; this.showLoader = false;
}); });
} }
-1
View File
@@ -44,7 +44,6 @@ export class AESEncrypt {
//Decrypting the string contained in cipherParams using the PBKDF2 key //Decrypting the string contained in cipherParams using the PBKDF2 key
var decrypted = CryptoJS.AES.decrypt(cipherParams, key128Bits1000Iterations, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7 }); var decrypted = CryptoJS.AES.decrypt(cipherParams, key128Bits1000Iterations, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7 });
console.log('AES decrypt',decrypted.toString(CryptoJS.enc.Utf8));
return decrypted.toString(CryptoJS.enc.Utf8); return decrypted.toString(CryptoJS.enc.Utf8);
} }
+1 -2
View File
@@ -6,8 +6,7 @@ import { StorageService } from './storage.service';
import { HttpClient, HttpHeaderResponse } from '@angular/common/http'; import { HttpClient, HttpHeaderResponse } from '@angular/common/http';
import { environment } from 'src/environments/environment'; import { environment } from 'src/environments/environment';
import { Storage } from '@ionic/storage'; import { Storage } from '@ionic/storage';
import { Message } from 'src/app/models/message.model';
import { Observable, Subject } from "rxjs/Rx";
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -180,14 +180,11 @@ export class ChatStorageService {
} }
} }
}) })
await this.storage.set('chatmsg' + roomId, messages) await this.storage.set('chatmsg' + roomId, messages)
}) })
} }
} }
+44 -41
View File
@@ -9,7 +9,8 @@ import { environment } from 'src/environments/environment';
import { showDateDuration } from 'src/plugin/showDateDuration'; import { showDateDuration } from 'src/plugin/showDateDuration';
import { ChatStorageService } from './chat-storage.service' import { ChatStorageService } from './chat-storage.service'
import { ChatMethodsService } from './chat-methods.service' import { ChatMethodsService } from './chat-methods.service'
import { MessageModel, DeleteMessageModel } from '../../models/beast-orm'
import { AESEncrypt } from '../aesencrypt.service'
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -31,6 +32,7 @@ export class MessageService {
t = '' t = ''
_id = '' _id = ''
id = '' // table id
_updatedAt _updatedAt
file file
attachments attachments
@@ -47,6 +49,7 @@ export class MessageService {
localReference = null localReference = null
viewed = [] viewed = []
received = [] received = []
addToDb = false
messageSend = false messageSend = false
@@ -54,10 +57,11 @@ export class MessageService {
private NfService: NfService, private NfService: NfService,
private WsChatService: WsChatService, private WsChatService: WsChatService,
private ChatStorageService: ChatStorageService, private ChatStorageService: ChatStorageService,
private ChatMethodsService: ChatMethodsService) { private ChatMethodsService: ChatMethodsService,
private AESEncrypt: AESEncrypt) {
} }
setData({customFields = {}, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData, localReference , viewed = [], received = []}:Message) { setData({customFields = {}, channels, mentions, msg ,rid ,ts, u, t, _id, id, _updatedAt, file, attachments, temporaryData, localReference , viewed = [], received = []}:Message) {
this.channels = channels || [] this.channels = channels || []
this.mentions = mentions || [] this.mentions = mentions || []
@@ -72,6 +76,7 @@ export class MessageService {
this.attachments = attachments this.attachments = attachments
this.temporaryData = temporaryData this.temporaryData = temporaryData
this.localReference = localReference || null this.localReference = localReference || null
this.id = id
this.viewed = [...new Set([...viewed,...this.viewed])]; this.viewed = [...new Set([...viewed,...this.viewed])];
this.received = [...new Set([...received,...this.received])]; this.received = [...new Set([...received,...this.received])];
@@ -210,7 +215,6 @@ export class MessageService {
type: 'reConnect', type: 'reConnect',
funx: async ()=> { funx: async ()=> {
this.send() this.send()
return true return true
} }
}) })
@@ -231,34 +235,12 @@ export class MessageService {
async redefinedMessage(ChatMessage , update = true) { async redefinedMessage(ChatMessage , update = true) {
ChatMessage = this.NfService.fix_updatedAt(ChatMessage) ChatMessage = this.NfService.fix_updatedAt(ChatMessage)
let reference
if(this._id) {
reference = '_id'
} else {
reference = 'localReference'
}
const message = this.getChatObj() 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) ChatMessage = Object.assign(message, ChatMessage)
if(update) {
await this.ChatStorageService.updateMessageDB(ChatMessage, this.rid, reference)
}
this.setData(ChatMessage) this.setData(ChatMessage)
await this.save()
} }
async downloadFileMsg() { async downloadFileMsg() {
@@ -277,8 +259,20 @@ export class MessageService {
return this.u.username != SessionStore.user.RochetChatUser return this.u.username != SessionStore.user.RochetChatUser
} }
async delete() { async delete(allMemberThatIsNotOffline) {
await this.ChatStorageService.deleteMessageFromDb(this._id, this.rid)
DeleteMessageModel.create({
messageId: this._id,
rid: this.rid,
ts: this.ts,
u: this.u,
receivedBy: allMemberThatIsNotOffline
})
const message = await MessageModel.get({_id: this._id})
await message.delete()
} }
isSenderIsNotMe(ChatMessage) { isSenderIsNotMe(ChatMessage) {
@@ -293,38 +287,47 @@ export class MessageService {
return { return {
channels: this.channels, channels: this.channels,
mentions: this.mentions, mentions: this.mentions,
msg: this.msg, //msg: this.AESEncrypt.encrypt(this.msg, SessionStore.user.RochetChatUser),
msg:this.msg,
rid: this.rid, rid: this.rid,
ts: this.ts, ts: this.ts,
u: this.u, u: this.u,
_id: this._id, _id: this._id,
id: this.id,
_updatedAt: this._updatedAt, _updatedAt: this._updatedAt,
messageSend: this.messageSend, messageSend: this.messageSend,
offline: this.offline, offline: this.offline,
viewed: this.viewed, viewed: this.viewed,
received: this.received, received: this.received,
localReference: this.localReference localReference: this.localReference,
attachments: this.attachments,
file: this.file
} }
} }
async addMessageDB() { async addMessageDB() {
if(!this.addToDb) {
this.addToDb= true
const message = this.getChatObj()
const message = this.getChatObj() delete message.id
const createdMessage = await MessageModel.create(message)
await this.ChatStorageService.addMessageDB(message, this.rid) this.id = createdMessage.id
}
} }
async save() { async save() {
const message = this.getChatObj() const message = this.getChatObj()
let reference await MessageModel.update(message)
if(this._id) {
reference = '_id'
} else {
reference = 'localReference'
}
await this.ChatStorageService.updateMessageDB(message, this.rid, reference)
} }
decryptMessage() {
try {
// this.msg = this.AESEncrypt.decrypt(this.msg, SessionStore.user.RochetChatUser)
} catch (error) {}
}
} }
+96 -107
View File
@@ -18,6 +18,10 @@ import { NfService } from 'src/app/services/chat/nf.service';
import { v4 as uuidv4 } from 'uuid' import { v4 as uuidv4 } from 'uuid'
import { ChatStorageService } from './chat-storage.service' import { ChatStorageService } from './chat-storage.service'
import { ChatMethodsService } from './chat-methods.service' import { ChatMethodsService } from './chat-methods.service'
import { MessageModel } from '../../models/beast-orm'
import { AESEncrypt } from '../aesencrypt.service'
import { IncomingChatMessage, ChatMessageInterface } from 'src/app/models/message.model';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
@@ -70,11 +74,12 @@ export class RoomService {
private chatService: ChatService, private chatService: ChatService,
private NfService: NfService, private NfService: NfService,
private ChatStorageService: ChatStorageService, private ChatStorageService: ChatStorageService,
private ChatMethodsService: ChatMethodsService private ChatMethodsService: ChatMethodsService,
private AESEncrypt: AESEncrypt
) { ) {
this.NativeNotificationService.askForPermission() this.NativeNotificationService.askForPermission()
this.restoreMessageFromDB() // this.restoreMessageFromDB()
this.WsChatService.getUserStatus((d) => { this.WsChatService.getUserStatus((d) => {
@@ -92,11 +97,12 @@ export class RoomService {
if(this.messages[index]._id) { if(this.messages[index]._id) {
try { try {
this.messages[index].received.push(userId) if(!this.messages[index].received.includes(userId)) {
this.messages[index].received.push(userId)
}
} catch(e) { } catch(e) {
this.messages[index].received = [userId] this.messages[index].received = [userId]
} }
this.messages[index].save() this.messages[index].save()
} }
@@ -109,7 +115,7 @@ export class RoomService {
} }
setData({members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService), _updatedAt }) { setData({members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt), _updatedAt }) {
this.customFields = customFields this.customFields = customFields
this.id = id this.id = id
this.name = name this.name = name
@@ -137,11 +143,11 @@ export class RoomService {
this.WsChatService.updateRoomEventss( this.WsChatService.updateRoomEventss(
this.id, this.id,
"stream-room-messages", "stream-room-messages",
async (_ChatMessage) => { async (IncomingChatMessage:IncomingChatMessage) => {
console.log('recivemessage', _ChatMessage) // console.log('recivemessage========', JSON.stringify(IncomingChatMessage))
let ChatMessage = _ChatMessage.fields.args[0] let IncomingChatMessageArgs = IncomingChatMessage.fields.args[0]
ChatMessage = this.fix_updatedAt(ChatMessage) let ChatMessage : ChatMessageInterface = this.fix_updatedAt(IncomingChatMessageArgs)
if(!this.messagesLocalReference.includes(ChatMessage.localReference)) { if(!this.messagesLocalReference.includes(ChatMessage.localReference)) {
@@ -208,6 +214,7 @@ export class RoomService {
this.otherUserType = args[1] this.otherUserType = args[1]
this.readAllMessage() this.readAllMessage()
} else { } else {
this.readAllMessage() this.readAllMessage()
} }
@@ -218,6 +225,30 @@ export class RoomService {
} }
getRoomMembersIds(): string[] {
return this.members.map((user)=> user._id)
}
getAllMemberThatIsNotOffline(): string[] {
const membersIds = this.getRoomMembersIds()
const allChatUsers = this.getAllUsers()
const AllMemberThatIsNotOffline = []
for(let user of allChatUsers) {
if(membersIds.includes(user._id)) {
if(user.status != 'offline') {
AllMemberThatIsNotOffline.push(user._id)
}
}
}
return AllMemberThatIsNotOffline
}
async receiveMessageDelete() { async receiveMessageDelete() {
this.WsChatService.updateRoomEventss( this.WsChatService.updateRoomEventss(
@@ -243,7 +274,8 @@ export class RoomService {
if(message._id == id) { if(message._id == id) {
this.messages.splice(index, 1) this.messages.splice(index, 1)
message.delete() const allMemberThatIsNotOffline = this.getAllMemberThatIsNotOffline()
message.delete(allMemberThatIsNotOffline)
//Get previous last message from room //Get previous last message from room
const previousLastMessage = this.messages.slice(-1)[0]; const previousLastMessage = this.messages.slice(-1)[0];
@@ -371,32 +403,36 @@ export class RoomService {
async restoreMessageFromDB() { async restoreMessageFromDB() {
if(environment.chatOffline) { if(environment.chatOffline) {
await this.storage.get('chatmsg' + this.id).then( async (messages = []) => { const messages = await MessageModel.filter({rid:this.id}).execute()
if(!Array.isArray(messages)) {
messages = []
}
await messages.forEach( async (ChatMessage, index) => { await messages.forEach( async (ChatMessage, index) => {
const wewMessage = await this.simplePrepareMessage(ChatMessage) const wewMessage = await this.simplePrepareMessage(ChatMessage)
if(wewMessage.offline == false) { if(wewMessage.offline == false) {
this.prepareMessage({message:ChatMessage}) const message = await this.prepareMessageCreateIfNotExist({message:ChatMessage})
} else {
const offlineMessage = await this.prepareMessageCreateIfNotExist({message:ChatMessage})
message?.decryptMessage()
} else {
const offlineMessage = await this.prepareMessageCreateIfNotExist({message:ChatMessage})
if(offlineMessage) {
this.messagesLocalReference.push(offlineMessage.localReference) this.messagesLocalReference.push(offlineMessage.localReference)
offlineMessage?.decryptMessage()
offlineMessage.send() offlineMessage.send()
} }
}); }
setTimeout(()=> { });
this.scrollDown()
}, 50)
}) setTimeout(()=> {
this.scrollDown()
}, 50)
} }
} }
@@ -417,41 +453,20 @@ export class RoomService {
await this.WsChatService.loadHistory(this.id, limit).then( async (chatHistory:chatHistory) => { await this.WsChatService.loadHistory(this.id, limit).then( async (chatHistory:chatHistory) => {
// await chatHistory.result.messages.reverse().forEach( async (message) => {})
const messagesId = this.messages.map((message)=> message._id) const messagesId = this.messages.map((message)=> message._id)
const createdMsgIds = []
chatHistory.result.messages.reverse().forEach(async(message) => { chatHistory.result.messages.reverse().forEach(async(message: any) => {
if (!messagesId.includes(message._id)) { if (!messagesId.includes(message._id)) {
createdMsgIds.push(message._id) const messagesToSave = await this.prepareMessageCreateIfNotExist({message: message});
await this.prepareMessageCreateIfNotExist({message: message}); if(messagesToSave) {
await messagesToSave.addMessageDB()
}
} }
const messagesToSave = this.messages.filter((message)=> createdMsgIds.includes(message._id)).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
}
})
await this.ChatStorageService.addManyMessageDB(messagesToSave, this.id)
}) })
await this.readMessage(chatHistory)
this.storage.set('chatmsg' + this.id, chatHistory.result.messages)
}) })
setTimeout(() => { setTimeout(() => {
@@ -461,70 +476,26 @@ export class RoomService {
this.hasLoadHistory = true 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() { async readAllMessage() {
const membersIds = this.members.map((user)=> user._id) const membersIds = this.members.map((user)=> user._id)
console.log('read all ===========')
await this.messages.forEach( async (message, index) => { await this.messages.forEach( async (message, index) => {
if(message._id) { if(message._id) {
if(message.viewed.length == 0) { if(message.viewed.length == 0) {
this.messages[index].viewed = membersIds this.messages[index].viewed = membersIds
this.messages[index].received = membersIds this.messages[index].received = membersIds
await this.messages[index].save()
} }
} }
}) })
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)
} }
/** /**
@@ -537,13 +508,11 @@ export class RoomService {
message = this.fix_updatedAt(message) message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService) const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt)
wewMessage.setData(message) wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory wewMessage.loadHistory = this.hasLoadHistory
if(!message?._id && environment.chatOffline && save) { if(!message?._id && environment.chatOffline && save) {
console.log('wewMessage.localReference ::', wewMessage.localReference)
this.messages.push(wewMessage) this.messages.push(wewMessage)
return wewMessage return wewMessage
} }
@@ -573,6 +542,27 @@ export class RoomService {
} }
async ChatMessageIsPresentInTheView(ChatMessage:ChatMessageInterface) {
let foundIndex;
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == ChatMessage._id) {
foundIndex = index
return true
} else {
return false
}
})
if (foundIndex) {
return { found, foundIndex}
} else {
return false
}
}
/** /**
* @description find or create message * @description find or create message
* @param message * @param message
@@ -582,7 +572,7 @@ export class RoomService {
async prepareCreate({message}): Promise<MessageService> { async prepareCreate({message}): Promise<MessageService> {
message = this.fix_updatedAt(message) message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService) const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt)
wewMessage.setData(message) wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory wewMessage.loadHistory = this.hasLoadHistory
@@ -595,10 +585,9 @@ export class RoomService {
} }
simplePrepareMessage(message) { simplePrepareMessage(message) {
message = this.fix_updatedAt(message) message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService) const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt)
wewMessage.setData(message) wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory wewMessage.loadHistory = this.hasLoadHistory
@@ -624,7 +613,7 @@ export class RoomService {
this.messages.push(wewMessage) this.messages.push(wewMessage)
return wewMessage return wewMessage
} else { } else {
return this.messages[foundIndex] return null
} }
} }
@@ -633,7 +622,7 @@ export class RoomService {
this._updatedAt = date || this._updatedAt this._updatedAt = date || this._updatedAt
} }
private fix_updatedAt(message) { private fix_updatedAt(message): ChatMessageInterface {
if (message?.result) { if (message?.result) {
message.result._updatedAt = message.result._updatedAt['$date'] message.result._updatedAt = message.result._updatedAt['$date']
} else if(message?._updatedAt) { } else if(message?._updatedAt) {
@@ -18,7 +18,7 @@ import { UserSession } from 'src/app/models/user.model';
import { AuthService } from '../auth.service'; import { AuthService } from '../auth.service';
import { ChatStorageService } from './chat-storage.service' import { ChatStorageService } from './chat-storage.service'
import { ChatMethodsService } from './chat-methods.service' import { ChatMethodsService } from './chat-methods.service'
import { AESEncrypt } from '../aesencrypt.service'
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -54,7 +54,8 @@ export class WsChatMethodsService {
private chatService: ChatService, private chatService: ChatService,
private authService: AuthService, private authService: AuthService,
private ChatStorageService: ChatStorageService, private ChatStorageService: ChatStorageService,
private ChatMethodsService:ChatMethodsService private ChatMethodsService:ChatMethodsService,
private AESEncrypt: AESEncrypt
) { ) {
this.loggedUser = authService.ValidatedUserChat['data']; this.loggedUser = authService.ValidatedUserChat['data'];
@@ -146,6 +147,8 @@ export class WsChatMethodsService {
try { try {
const rooms = await this.storage.get('Rooms'); const rooms = await this.storage.get('Rooms');
console.log('restore',rooms)
if(rooms) { if(rooms) {
await rooms.result.update.forEach( async (roomData: room) => { await rooms.result.update.forEach( async (roomData: room) => {
await this.prepareRoom(roomData); await this.prepareRoom(roomData);
@@ -163,9 +166,6 @@ export class WsChatMethodsService {
const rooms = await this.WsChatService.getRooms(); const rooms = await this.WsChatService.getRooms();
await this.storage.remove('Rooms'); await this.storage.remove('Rooms');
console.log('rooms ============', rooms)
await rooms.result.update.forEach( async (roomData: room, index) => { await rooms.result.update.forEach( async (roomData: room, index) => {
const roomId = this.getRoomId(roomData); const roomId = this.getRoomId(roomData);
@@ -199,8 +199,8 @@ export class WsChatMethodsService {
}); });
console.log('save rooms', rooms)
await this.storage.set('Rooms', rooms); await this.storage.set('Rooms', rooms);
console.log(rooms.result.update, 'rooms.result.update')
this.sortRoomList() this.sortRoomList()
this.loadingWholeList = false this.loadingWholeList = false
@@ -291,7 +291,7 @@ export class WsChatMethodsService {
// create room // create room
if(!this.roomExist(roomId)) { if(!this.roomExist(roomId)) {
let room:RoomService = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService , this.ChatStorageService, this.ChatMethodsService) let room:RoomService = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService , this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt)
room.setData(setData) room.setData(setData)
room.receiveMessage() room.receiveMessage()
room.getAllUsers = this.getUsers room.getAllUsers = this.getUsers
@@ -48,15 +48,13 @@
</mat-menu> </mat-menu>
</div> </div>
<div class="title"> <div class="title">
<ion-label>{{msg.u.name}}</ion-label> <ion-label>{{msg.u.name}} </ion-label>
<span class="time">{{msg.duration}}</span> <span class="time">{{msg.duration}}</span>
</div> </div>
<div class="d-flex justify-space-between"> <div class="d-flex justify-space-between">
<ion-label class="flex-0">{{msg.msg}} </ion-label> <ion-label class="flex-0">{{msg.msg}} </ion-label>
<ion-label class="float-status-all float-status" > <ion-label class="float-status-all float-status" >
<ion-icon *ngIf="msg.messageSend == false" src="assets/images/clock-regular.svg"></ion-icon> <ion-icon *ngIf="msg.messageSend == false" src="assets/images/clock-regular.svg"></ion-icon>
<ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0" src="assets/images/check-solid.svg"></ion-icon> <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0" src="assets/images/check-solid.svg"></ion-icon>
<ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon>
@@ -76,7 +74,7 @@
</mat-menu> </mat-menu>
</div> </div>
<div class="title"> <div class="title">
<ion-label>{{msg.u.name}} </ion-label> <ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{msg.duration}}</span> <span class="time">{{msg.duration}}</span>
</div> </div>
<div> <div>
@@ -328,14 +328,12 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
} }
getChatMembers() { getChatMembers() {
console.log(this.roomId); // console.log(this.roomId);
//this.showLoader = true; //this.showLoader = true;
this.chatService.getMembers(this.roomId).subscribe(res => { this.chatService.getMembers(this.roomId).subscribe(res => {
this.members = res['members']; this.members = res['members'];
this.dmUsers = res['members'].filter(data => data.username != this.loggedUser.me.username) this.dmUsers = res['members'].filter(data => data.username != this.loggedUser.me.username)
console.log('this.dmUsers', res);
console.log(this.dmUsers);
this.showLoader = false; this.showLoader = false;
}); });
} }