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__
plugins_
ios
src/plugin/beast-orm
+5
View File
@@ -6151,6 +6151,11 @@
"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": {
"version": "1.6.49",
"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-svg-icon": "^12.0.0",
"angular-tag-cloud-module": "^5.2.2",
"beast-orm": "0.0.7",
"bootstrap": "^4.5.0",
"build": "0.1.4",
"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 { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
import { StorageService } from 'src/app/services/storage.service';
import { MessageModel } from './models/beast-orm'
const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
parse: {
@@ -120,7 +120,7 @@ export class ChatOptionsFeaturesPage implements OnInit {
}
this.chatService.sendMessage(body).subscribe(res=> {
console.log(res);
// console.log(res);
},(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 {
customFields:any;
_id: string;
id: null | string;
rid: string;
msg: string;
ts: Ts;
+45 -3
View File
@@ -1,4 +1,46 @@
export interface Message {
author: string;
message: string;
export interface IncomingChatMessage {
msg: 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 { EditGroupPage } from 'src/app/shared/chat/edit-group/edit-group.page';
import * as Rx from "rxjs/Rx";
import { Message } from 'src/app/models/message.model';
import { Observable, Subject } from "rxjs/Rx";
import { NavigationStart, NavigationEnd, Router } from '@angular/router';
import { EventPerson } from 'src/app/models/eventperson.model';
@@ -143,10 +142,6 @@ export class ChatPage implements OnInit {
ngOnInit() {
console.log('Rooms INDIVIDUAIS',this.wsChatMethodsService._dm);
console.log(' ROOMS GROUP',this.wsChatMethodsService._group);
this.segment = "Contactos";
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.members = res['members'];
this.dmUsers = res['members'].filter(data => data.username != this.loggedUser.me.username)
console.log(res);
console.log(this.dmUsers);
this.showLoader = false;
});
}
-1
View File
@@ -44,7 +44,6 @@ export class AESEncrypt {
//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 });
console.log('AES decrypt',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 { environment } from 'src/environments/environment';
import { Storage } from '@ionic/storage';
import { Message } from 'src/app/models/message.model';
import { Observable, Subject } from "rxjs/Rx";
@Injectable({
providedIn: 'root'
@@ -180,14 +180,11 @@ export class ChatStorageService {
}
}
})
await this.storage.set('chatmsg' + roomId, messages)
})
}
}
+42 -39
View File
@@ -9,7 +9,8 @@ import { environment } from 'src/environments/environment';
import { showDateDuration } from 'src/plugin/showDateDuration';
import { ChatStorageService } from './chat-storage.service'
import { ChatMethodsService } from './chat-methods.service'
import { MessageModel, DeleteMessageModel } from '../../models/beast-orm'
import { AESEncrypt } from '../aesencrypt.service'
@Injectable({
providedIn: 'root'
@@ -31,6 +32,7 @@ export class MessageService {
t = ''
_id = ''
id = '' // table id
_updatedAt
file
attachments
@@ -47,6 +49,7 @@ export class MessageService {
localReference = null
viewed = []
received = []
addToDb = false
messageSend = false
@@ -54,10 +57,11 @@ export class MessageService {
private NfService: NfService,
private WsChatService: WsChatService,
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.mentions = mentions || []
@@ -72,6 +76,7 @@ export class MessageService {
this.attachments = attachments
this.temporaryData = temporaryData
this.localReference = localReference || null
this.id = id
this.viewed = [...new Set([...viewed,...this.viewed])];
this.received = [...new Set([...received,...this.received])];
@@ -210,7 +215,6 @@ export class MessageService {
type: 'reConnect',
funx: async ()=> {
this.send()
return true
}
})
@@ -231,34 +235,12 @@ export class MessageService {
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)
await this.save()
}
async downloadFileMsg() {
@@ -277,8 +259,20 @@ export class MessageService {
return this.u.username != SessionStore.user.RochetChatUser
}
async delete() {
await this.ChatStorageService.deleteMessageFromDb(this._id, this.rid)
async delete(allMemberThatIsNotOffline) {
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) {
@@ -293,38 +287,47 @@ export class MessageService {
return {
channels: this.channels,
mentions: this.mentions,
//msg: this.AESEncrypt.encrypt(this.msg, SessionStore.user.RochetChatUser),
msg:this.msg,
rid: this.rid,
ts: this.ts,
u: this.u,
_id: this._id,
id: this.id,
_updatedAt: this._updatedAt,
messageSend: this.messageSend,
offline: this.offline,
viewed: this.viewed,
received: this.received,
localReference: this.localReference
localReference: this.localReference,
attachments: this.attachments,
file: this.file
}
}
async addMessageDB() {
if(!this.addToDb) {
this.addToDb= true
const message = this.getChatObj()
await this.ChatStorageService.addMessageDB(message, this.rid)
delete message.id
const createdMessage = await MessageModel.create(message)
this.id = createdMessage.id
}
}
async save() {
const message = this.getChatObj()
let reference
if(this._id) {
reference = '_id'
} else {
reference = 'localReference'
await MessageModel.update(message)
}
await this.ChatStorageService.updateMessageDB(message, this.rid, reference)
decryptMessage() {
try {
// this.msg = this.AESEncrypt.decrypt(this.msg, SessionStore.user.RochetChatUser)
} catch (error) {}
}
}
+87 -98
View File
@@ -18,6 +18,10 @@ import { NfService } from 'src/app/services/chat/nf.service';
import { v4 as uuidv4 } from 'uuid'
import { ChatStorageService } from './chat-storage.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({
providedIn: 'root'
})
@@ -70,11 +74,12 @@ export class RoomService {
private chatService: ChatService,
private NfService: NfService,
private ChatStorageService: ChatStorageService,
private ChatMethodsService: ChatMethodsService
private ChatMethodsService: ChatMethodsService,
private AESEncrypt: AESEncrypt
) {
this.NativeNotificationService.askForPermission()
this.restoreMessageFromDB()
// this.restoreMessageFromDB()
this.WsChatService.getUserStatus((d) => {
@@ -92,11 +97,12 @@ export class RoomService {
if(this.messages[index]._id) {
try {
if(!this.messages[index].received.includes(userId)) {
this.messages[index].received.push(userId)
}
} catch(e) {
this.messages[index].received = [userId]
}
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.id = id
this.name = name
@@ -137,11 +143,11 @@ export class RoomService {
this.WsChatService.updateRoomEventss(
this.id,
"stream-room-messages",
async (_ChatMessage) => {
console.log('recivemessage', _ChatMessage)
async (IncomingChatMessage:IncomingChatMessage) => {
// console.log('recivemessage========', JSON.stringify(IncomingChatMessage))
let ChatMessage = _ChatMessage.fields.args[0]
ChatMessage = this.fix_updatedAt(ChatMessage)
let IncomingChatMessageArgs = IncomingChatMessage.fields.args[0]
let ChatMessage : ChatMessageInterface = this.fix_updatedAt(IncomingChatMessageArgs)
if(!this.messagesLocalReference.includes(ChatMessage.localReference)) {
@@ -208,6 +214,7 @@ export class RoomService {
this.otherUserType = args[1]
this.readAllMessage()
} else {
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() {
this.WsChatService.updateRoomEventss(
@@ -243,7 +274,8 @@ export class RoomService {
if(message._id == id) {
this.messages.splice(index, 1)
message.delete()
const allMemberThatIsNotOffline = this.getAllMemberThatIsNotOffline()
message.delete(allMemberThatIsNotOffline)
//Get previous last message from room
const previousLastMessage = this.messages.slice(-1)[0];
@@ -371,33 +403,37 @@ export class RoomService {
async restoreMessageFromDB() {
if(environment.chatOffline) {
await this.storage.get('chatmsg' + this.id).then( async (messages = []) => {
if(!Array.isArray(messages)) {
messages = []
}
const messages = await MessageModel.filter({rid:this.id}).execute()
await messages.forEach( async (ChatMessage, index) => {
const wewMessage = await this.simplePrepareMessage(ChatMessage)
if(wewMessage.offline == false) {
this.prepareMessage({message:ChatMessage})
const message = await this.prepareMessageCreateIfNotExist({message:ChatMessage})
message?.decryptMessage()
} else {
const offlineMessage = await this.prepareMessageCreateIfNotExist({message:ChatMessage})
if(offlineMessage) {
this.messagesLocalReference.push(offlineMessage.localReference)
offlineMessage?.decryptMessage()
offlineMessage.send()
}
}
});
setTimeout(()=> {
this.scrollDown()
}, 50)
})
}
}
@@ -417,41 +453,20 @@ export class RoomService {
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 createdMsgIds = []
chatHistory.result.messages.reverse().forEach(async(message) => {
chatHistory.result.messages.reverse().forEach(async(message: any) => {
if (!messagesId.includes(message._id)) {
createdMsgIds.push(message._id)
await this.prepareMessageCreateIfNotExist({message: message});
const messagesToSave = 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(() => {
@@ -461,70 +476,26 @@ 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)
console.log('read all ===========')
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.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)
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.loadHistory = this.hasLoadHistory
if(!message?._id && environment.chatOffline && save) {
console.log('wewMessage.localReference ::', wewMessage.localReference)
this.messages.push(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
* @param message
@@ -582,7 +572,7 @@ export class RoomService {
async prepareCreate({message}): Promise<MessageService> {
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.loadHistory = this.hasLoadHistory
@@ -595,10 +585,9 @@ export class RoomService {
}
simplePrepareMessage(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.loadHistory = this.hasLoadHistory
@@ -624,7 +613,7 @@ export class RoomService {
this.messages.push(wewMessage)
return wewMessage
} else {
return this.messages[foundIndex]
return null
}
}
@@ -633,7 +622,7 @@ export class RoomService {
this._updatedAt = date || this._updatedAt
}
private fix_updatedAt(message) {
private fix_updatedAt(message): ChatMessageInterface {
if (message?.result) {
message.result._updatedAt = message.result._updatedAt['$date']
} else if(message?._updatedAt) {
@@ -18,7 +18,7 @@ import { UserSession } from 'src/app/models/user.model';
import { AuthService } from '../auth.service';
import { ChatStorageService } from './chat-storage.service'
import { ChatMethodsService } from './chat-methods.service'
import { AESEncrypt } from '../aesencrypt.service'
@Injectable({
providedIn: 'root'
@@ -54,7 +54,8 @@ export class WsChatMethodsService {
private chatService: ChatService,
private authService: AuthService,
private ChatStorageService: ChatStorageService,
private ChatMethodsService:ChatMethodsService
private ChatMethodsService:ChatMethodsService,
private AESEncrypt: AESEncrypt
) {
this.loggedUser = authService.ValidatedUserChat['data'];
@@ -146,6 +147,8 @@ export class WsChatMethodsService {
try {
const rooms = await this.storage.get('Rooms');
console.log('restore',rooms)
if(rooms) {
await rooms.result.update.forEach( async (roomData: room) => {
await this.prepareRoom(roomData);
@@ -163,9 +166,6 @@ export class WsChatMethodsService {
const rooms = await this.WsChatService.getRooms();
await this.storage.remove('Rooms');
console.log('rooms ============', rooms)
await rooms.result.update.forEach( async (roomData: room, index) => {
const roomId = this.getRoomId(roomData);
@@ -199,8 +199,8 @@ export class WsChatMethodsService {
});
console.log('save rooms', rooms)
await this.storage.set('Rooms', rooms);
console.log(rooms.result.update, 'rooms.result.update')
this.sortRoomList()
this.loadingWholeList = false
@@ -291,7 +291,7 @@ export class WsChatMethodsService {
// create room
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.receiveMessage()
room.getAllUsers = this.getUsers
@@ -55,8 +55,6 @@
<ion-label class="flex-0">{{msg.msg}} </ion-label>
<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 == 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>
@@ -328,14 +328,12 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}
getChatMembers() {
console.log(this.roomId);
// console.log(this.roomId);
//this.showLoader = true;
this.chatService.getMembers(this.roomId).subscribe(res => {
this.members = res['members'];
this.dmUsers = res['members'].filter(data => data.username != this.loggedUser.me.username)
console.log('this.dmUsers', res);
console.log(this.dmUsers);
this.showLoader = false;
});
}