Websocket with storage

This commit is contained in:
Eudes Inácio
2022-01-20 14:31:49 +01:00
parent 4d9db4f198
commit e86d9d8b35
3 changed files with 247 additions and 96 deletions
+52 -24
View File
@@ -12,28 +12,30 @@ import { Storage } from '@ionic/storage';
export class RoomService { export class RoomService {
massages: MessageService[] = [] massages: MessageService[] = []
storageMessage: any[] = [];
lastMessage: MessageService; lastMessage: MessageService;
chatUser: ChatUserService[] = [] chatUser: ChatUserService[] = []
customFields:any; customFields: any;
id = '' id = ''
t = '' t = ''
name = '' name = ''
_updatedAt = {} _updatedAt = {}
private hasLoadHistory = false private hasLoadHistory = false
duration = '' duration = ''
private ToastService = ToastsService private ToastService = ToastsService
mgsArray = [];
scrollDown = () => {} scrollDown = () => { }
constructor( constructor(
public WsChatService: WsChatService, public WsChatService: WsChatService,
private MessageService: MessageService, private MessageService: MessageService,
private storage: Storage, private storage: Storage,
) {} ) { }
setData({customFields, id, name, t, lastMessage, _updatedAt}) { setData({ customFields, id, name, t, lastMessage, _updatedAt }) {
this.customFields = customFields this.customFields = customFields
this.id = id this.id = id
this.name = name this.name = name
@@ -57,11 +59,11 @@ export class RoomService {
const message = new MessageService() const message = new MessageService()
message.setData(ChatMessage) message.setData(ChatMessage)
this.lastMessage.msg = message.msg this.lastMessage.msg = message.msg
if(message.t == 'r'){this.name = message.msg} if (message.t == 'r') { this.name = message.msg }
this.calDateDuration(ChatMessage._updatedAt) this.calDateDuration(ChatMessage._updatedAt)
this.massages.push(message) this.massages.push(message)
setTimeout(()=>{ setTimeout(() => {
this.scrollDown() this.scrollDown()
}, 100) }, 100)
@@ -74,19 +76,34 @@ export class RoomService {
} }
// runs onces only // runs onces only
loadHistory(limit= 100) { loadHistory(limit = 100) {
if(this.hasLoadHistory){ return false} if (this.hasLoadHistory) { return false }
this.WsChatService.loadHistory(this.id, limit).then(async (chatHistory:chatHistory) => { this.WsChatService.loadHistory(this.id, limit).then(async (chatHistory: chatHistory) => {
await this.transformData(chatHistory.result.messages.reverse()); //await this.transformData(chatHistory.result.messages.reverse());
/* console.log('loadHistory 111', chatHistory.result.messages.reverse())
this.mgsArray = chatHistory.result.messages.reverse();
await this.storage.set('chatmsg', this.mgsArray).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
}); */
/* await this.storage.get('chatmsg').then((message) => {
message.forEach(message => {
console.log('FROM DB WEB', message)
message = this.fix_updatedAt(message)
const wewMessage = new MessageService()
wewMessage.setData(message)
this.massages.push(wewMessage)
console.log('loadHistory 222', this.massages)
});
}) */
chatHistory.result.messages.reverse().forEach(message => { chatHistory.result.messages.reverse().forEach(message => {
message = this.fix_updatedAt(message) message = this.fix_updatedAt(message)
console.log('loadHistory', message) console.log('loadHistory', message)
this.storageMessage.push(message)
const wewMessage = new MessageService() const wewMessage = new MessageService()
wewMessage.setData(message) wewMessage.setData(message)
this.massages.push(wewMessage) this.massages.push(wewMessage)
@@ -95,18 +112,27 @@ export class RoomService {
}) })
setTimeout(()=>{ setTimeout(() => {
this.scrollDown() this.scrollDown()
}, 50) }, 50)
this.hasLoadHistory = true this.hasLoadHistory = true
} }
updateMeessage(messageID, imgbase64) {
}
async returnData(res) {
return res;
}
async transformData(res) { async transformData(res) {
let mgsArray = []; this.mgsArray = [];
res.forEach(async element => { res.forEach(async element => {
console.log('TRANSFORM DATA ELEMENT' ,element)
if (element.file) { if (element.file) {
if (element.file.guid) { if (element.file.guid) {
@@ -125,11 +151,11 @@ export class RoomService {
rid: element.rid, rid: element.rid,
ts: element.ts, ts: element.ts,
u: element.u, u: element.u,
_updatedAt: element._updatedAt, _updatedAt: element._updatedAt ,
} }
mgsArray.push(this.fix_updatedAt(chatmsg)); this.mgsArray.push(chatmsg);
}) })
} else { } else {
@@ -146,7 +172,7 @@ export class RoomService {
_updatedAt: element._updatedAt, _updatedAt: element._updatedAt,
} }
mgsArray.push(this.fix_updatedAt(chatmsg)) this.mgsArray.push(chatmsg)
} }
} else { } else {
let chatmsg = { let chatmsg = {
@@ -161,20 +187,20 @@ export class RoomService {
_updatedAt: element._updatedAt, _updatedAt: element._updatedAt,
} }
mgsArray.push(this.fix_updatedAt(chatmsg)) this.mgsArray.push(chatmsg)
} }
}); });
await this.storage.remove('chatmsg').then(() => { await this.storage.remove('chatmsg').then(() => {
console.log('MSG REMOVE FROM STORAGE') console.log('MSG REMOVE FROM STORAGE')
}); });
await this.storage.set('chatmsg', mgsArray).then((value) => { await this.storage.set('chatmsg', this.mgsArray).then((value) => {
console.log('MSG SAVED ON STORAGE', value) console.log('MSG SAVED ON STORAGE', value)
}); });
} }
ReactToMessage() {} ReactToMessage() { }
private calDateDuration(date = null) { private calDateDuration(date = null) {
this.duration = showDateDuration(date || this._updatedAt); this.duration = showDateDuration(date || this._updatedAt);
@@ -182,9 +208,11 @@ export class RoomService {
private fix_updatedAt(message) { private fix_updatedAt(message) {
if(message.result) { if (message.result) {
console.log('FIX UPDATE ', message.result)
message.result._updatedAt = message.result._updatedAt['$date'] message.result._updatedAt = message.result._updatedAt['$date']
} else{ } else {
console.log('FIX UPDATE 11', message)
message._updatedAt = message._updatedAt['$date'] message._updatedAt = message._updatedAt['$date']
} }
return message return message
@@ -192,6 +220,6 @@ export class RoomService {
// to add // to add
countDownDate(){} countDownDate() { }
} }
+24 -22
View File
@@ -38,7 +38,7 @@
</ion-refresher-content> </ion-refresher-content>
</ion-refresher> </ion-refresher>
<div class="messages" #scrollMe> <div class="messages" #scrollMe>
<div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of messages; let last = last"> <div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of wsChatMethodsService.getDmRoom(roomId).massages; let last = last">
<div class='message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45' *ngIf="msg.msg !=''"> <div class='message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45' *ngIf="msg.msg !=''">
<div class="message-item-options d-flex justify-content-end"> <div class="message-item-options d-flex justify-content-end">
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"> <fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer">
@@ -113,30 +113,32 @@
</div> </div>
<div class='message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45' *ngIf="msg.msg ==''"> <div class='message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45' *ngIf="msg.msg ==''">
<div *ngIf="msg.file.type == 'application/img'"> <div *ngIf="msg.file">
<div class="message-item-options d-flex justify-content-end"> <div *ngIf="msg.file.type == 'application/img'">
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"> <div class="message-item-options d-flex justify-content-end">
</fa-icon> <fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer">
<mat-menu #beforeMenu="matMenu" xPosition="before"> </fa-icon>
<button (click)="deleteMessage(msg._id)" class="menuButton">Apagar mensagem</button> <mat-menu #beforeMenu="matMenu" xPosition="before">
</mat-menu> <button (click)="deleteMessage(msg._id)" class="menuButton">Apagar mensagem</button>
</div> </mat-menu>
<div class="title"> </div>
<ion-label>{{msg.u.name}}</ion-label> <div class="title">
<span class="time">{{showDateDuration(msg._updatedAt)}}</span> <ion-label>{{msg.u.name}}</ion-label>
</div> <span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<div> </div>
<ion-label>{{msg.msg}}</ion-label> <div>
<div *ngIf="msg.file" class="message-attachments"> <ion-label>{{msg.msg}}</ion-label>
<div> <div *ngIf="msg.file" class="message-attachments">
<div (click)="openPreview(msg)"> <div>
<!-- <img *ngIf="file.image_url" src="{{file.image_url}}" alt="image" (click)="imageSize(file.image_url)"> --> <div (click)="openPreview(msg)">
TTTT <!-- <img *ngIf="file.image_url" src="{{file.image_url}}" alt="image" (click)="imageSize(file.image_url)"> -->
<img *ngIf="msg.file.image_url" src="{{msg.file.image_url}}" alt="image"> TTTT
<img *ngIf="msg.file.image_url" src="{{msg.file.image_url}}" alt="image">
</div>
</div> </div>
</div> </div>
{{last ? scrollToBottom() : ''}}
</div> </div>
{{last ? scrollToBottom() : ''}}
</div> </div>
</div> </div>
</div> </div>
+162 -41
View File
@@ -23,8 +23,10 @@ import { StorageService } from 'src/app/services/storage.service';
import { Directory, Filesystem } from '@capacitor/filesystem'; import { Directory, Filesystem } from '@capacitor/filesystem';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { Storage } from '@ionic/storage'; import { Storage } from '@ionic/storage';
import { WsChatMethodsService} from 'src/app/services/chat/ws-chat-methods.service' import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.service'
import { WsChatService } from 'src/app/services/chat/ws-chat.service' import { WsChatService } from 'src/app/services/chat/ws-chat.service'
import { MessageService } from 'src/app/services/chat/message.service';
import { element } from 'protractor';
const IMAGE_DIR = 'stored-images'; const IMAGE_DIR = 'stored-images';
@Component({ @Component({
@@ -68,6 +70,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
longPressActive = false; longPressActive = false;
frameUrl: any; frameUrl: any;
downloadFile: any; downloadFile: any;
massages: MessageService[] = []
constructor( constructor(
public popoverController: PopoverController, public popoverController: PopoverController,
@@ -100,9 +103,17 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory() this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory()
this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked
this.getMessageDB(); /* console.log('DATATATA', this.wsChatMethodsService.getDmRoom(this.roomId).massages)
this.wsChatMethodsService.getDmRoom(this.roomId).massages.forEach((element) => {
console.log('DATATATA 11', element)
}) */
setTimeout(()=>{
//this.transformData(this.wsChatMethodsService.getDmRoom(this.roomId).massages)
//this.getMessageDB()
setTimeout(() => {
this.scrollToBottomClicked() this.scrollToBottomClicked()
}, 50) }, 50)
@@ -115,6 +126,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
} }
onPressingMessage() { onPressingMessage() {
const gesture = this.gestureController.create({ const gesture = this.gestureController.create({
el: this.messageContainer.nativeElement, el: this.messageContainer.nativeElement,
@@ -242,7 +254,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
this.message = ""; this.message = "";
} }
deleteMessage(msgId:string) { deleteMessage(msgId: string) {
let body = { let body = {
"roomId": this.roomId, "roomId": this.roomId,
"msgId": msgId, "msgId": msgId,
@@ -254,23 +266,128 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}); */ }); */
} }
getMessageDB() { async getMessageDB() {
this.storage.get('chatmsg').then((msg) => { await this.storage.get('chatmsg').then((message) => {
this.transformData(message)
/* message.forEach(message => {
console.log('FROM DB WEB', message)
message = this.fix_updatedAt(message)
const wewMessage = new MessageService()
wewMessage.setData(message)
this.massages.push(wewMessage)
console.log('loadHistory 222', this.massages)
}); */
})
/* await this.storage.get('chatmsg').then((msg) => {
console.log('FROM DB WEB', msg) console.log('FROM DB WEB', msg)
let msgArray = []; let msgArray = [];
msgArray = msg; if (msg) {
msgArray.filter(data => data._id != this.roomId); msgArray = msg;
this.messages = msgArray; msgArray.filter(data => data._id != this.roomId);
console.log("MSG CHAT WEB", this.messages) this.messages = msgArray;
}) console.log("MSG CHAT WEB", this.messages)
} else {
this.getMessageDB()
}
}) */
}
private fix_updatedAt(message) {
if (message.result) {
console.log('FIX UPDATE ', message.result)
message.result._updatedAt = message.result._updatedAt['$date']
} else {
console.log('FIX UPDATE 11', message)
message._updatedAt = message._updatedAt['$date']
}
return message
} }
async transformData(res) { async transformData(res) {
let mgsArray = []; let mgsArray = [];
res.forEach(async element => { res.forEach(async element => {
console.log('TRANSFORM DATA ELEMENT' ,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 ,
}
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,
}
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,
}
mgsArray.push(chatmsg)
}
});
await this.storage.remove('chatmsg').then(() => {
console.log('MSG REMOVE FROM STORAGE')
});
await this.storage.set('chatmsg', mgsArray).then((message) => {
message.forEach(message => {
console.log('FROM DB WEB', message)
message = this.fix_updatedAt(message)
const wewMessage = new MessageService()
wewMessage.setData(message)
this.massages.push(wewMessage)
console.log('loadHistory 222', this.massages)
});
});
}
/* async transformData(res) {
console.log('TRANSFORM DATA', res)
let mgsArray = [];
res.map(async element => {
console.log('TRANSFORM DATA ELEMENT', element)
if (element.file) { if (element.file) {
if (element.file.guid) { if (element.file.guid) {
@@ -336,11 +453,11 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
console.log('MSG SAVED ON STORAGE', value) console.log('MSG SAVED ON STORAGE', value)
}); });
} } */
async viewDocument(msg:any, url?:string){ async viewDocument(msg: any, url?: string) {
if(msg.file.type == "application/img"){ if (msg.file.type == "application/img") {
let response:any = await this.fileService.getFile(msg.file.guid).toPromise(); let response: any = await this.fileService.getFile(msg.file.guid).toPromise();
console.log(response); console.log(response);
alert(response); alert(response);
@@ -625,34 +742,35 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
console.log('serverLongPull', res['success']); console.log('serverLongPull', res['success']);
if (res['success'] == true) { if (res['success'] == true) {
// Show Error // Show Error
//showMessage(response.statusText); //showMessage(response.statusText);
/* this.messages = res['messages'].reverse(); /* this.messages = res['messages'].reverse();
this.chatMessageStore.add(roomId, this.messages) */ this.chatMessageStore.add(roomId, this.messages) */
console.log('MSG FROM ROCKET ', res['messages'].reverse()) console.log('MSG FROM ROCKET ', res['messages'].reverse())
/* this.transformData(res['messages'].reverse()); /* this.transformData(res['messages'].reverse());
this.getMessageDB(); */ this.getMessageDB(); */
//console.log(this.messages); //console.log(this.messages);
// Reconnect in one second // Reconnect in one second
if(this.route.url != "/home/chat"){ if (this.route.url != "/home/chat") {
console.log("Timer message stop") console.log("Timer message stop")
} }
else{ else {
if(document.querySelector('app-messages')){ if (document.querySelector('app-messages')) {
await new Promise(resolve => setTimeout(resolve, 5000)); await new Promise(resolve => setTimeout(resolve, 5000));
// await this.serverLongPull(); // await this.serverLongPull();
this.getDirectMessages.emit(); this.getDirectMessages.emit();
console.log('Timer message running') console.log('Timer message running')
}
} }
} }
} }, (error) => {
}, (error) => { console.log(error);
console.log(error); });
});
} }
sliderOpts = { sliderOpts = {
zoom: false, zoom: false,
slidesPerView: 1.5, slidesPerView: 1.5,
@@ -709,7 +827,9 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
} else if (event.type === HttpEventType.Response) { } else if (event.type === HttpEventType.Response) {
this.downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); this.downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
this.storage.set(msg.file.guid, this.downloadFile); await this.storage.set(msg.file.guid, this.downloadFile).then(() => {
console.log('IMAGE SAVED')
});
} }
}); });
@@ -721,12 +841,13 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
async openPreview(msg) { async openPreview(msg) {
if (msg.file.image_url === null) { if (msg.file.image_url === null) {
this.downloadFileMsg(msg) this.downloadFileMsg(msg)
} else { } else {
const modal = await this.modalController.create({ const modal = await this.modalController.create({
component: ViewMediaPage, component: ViewMediaPage,
cssClass: 'modal modal-desktop', cssClass: 'modal modal-desktop',
componentProps: { componentProps: {
image: msg.attachments[0].image_url, image: msg.file.image_url,
username: msg.u.name, username: msg.u.name,
_updatedAt: msg._updatedAt _updatedAt: msg._updatedAt
} }