bug fix afaster adding sqlite to chat stop presenting msg on web

This commit is contained in:
Eudes Inácio
2021-12-08 22:49:14 +01:00
parent f7add4dfa5
commit 796143d7c4
2 changed files with 187 additions and 176 deletions
+13 -5
View File
@@ -144,6 +144,8 @@ export class ChatPage implements OnInit {
this.loggedUser = res;
console.log(this.loggedUser);
this.load();
this.getDirectMessagesDB();
});
/* websocket functions */
@@ -490,12 +492,15 @@ export class ChatPage implements OnInit {
console.log('Chat list', res);
if (res != 200) {
//console.log(res.ims);
/* this.userDirectMessages = res.ims.sort((a, b) => {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.userDirectMessages = res.ims.sort((a, b) => {
var dateA = new Date(a._updatedAt).getTime();
var dateB = new Date(b._updatedAt).getTime();
return dateB - dateA;
}); */
});
}
//console.log(res.ims);
//console.log(this.userDirectMessages);
if (this.route.url != "/home/chat") {
@@ -535,8 +540,11 @@ export class ChatPage implements OnInit {
console.log('chatusers', res);
this.transformDataUserList(res['users'])
//this.dmUsers = res['users'].filter(data => data.username != this.loggedUserChat.me.username);
//console.log(this.dmUsers);
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.dmUsers = res['users'].filter(data => data.username != this.loggedUserChat.me.username);
console.log(this.dmUsers);
}
});
}
+174 -171
View File
@@ -1,5 +1,5 @@
import { AfterViewChecked, AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router'
import { ActivatedRoute, Router } from '@angular/router'
import { GestureController, Gesture, ModalController, NavParams, PopoverController, IonSlides, Platform } from '@ionic/angular';
import { map } from 'rxjs/operators';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
@@ -39,20 +39,20 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
showLoader: boolean;
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
/* @ViewChild('messageContainer') messageContainer: ElementRef; */
/* @ViewChild('messageContainer') messageContainer: ElementRef; */
@ViewChild('rectangle') private rectangle: ElementRef;
canvas: any
ctx: any
loggedUser: any;
message = '';
messages:any;
userPresence='';
dmUsers:any;
roomId:string;
el:any;
members:any;
scrollingOnce:boolean = true;
messages: any;
userPresence = '';
dmUsers: any;
roomId: string;
el: any;
members: any;
scrollingOnce: boolean = true;
chatMessageStore = ChatMessageStore;
chatUserStorage = ChatUserStorage;
@@ -64,11 +64,11 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
attendees: EventPerson[] = [];
longPressActive = false;
showMessageOptions = false;
selectedMsgId:string;
selectedMsgId: string;
dicIndex = 0;
task: ExpedientTaskModalPageNavParamsTask;
LoadedDocument:any = null;
LoadedDocument: any = null;
recording = false;
storedFileNames = [];
@@ -100,7 +100,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
console.log('ROOM ID', this.roomId)
window.onresize = (event) => {
if( window.innerWidth > 701){
if (window.innerWidth > 701) {
this.modalController.dismiss();
}
};
@@ -133,7 +133,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.startRecording();
this.calculateDuration();
},
onEnd: ev =>{
onEnd: ev => {
Haptics.impact({ style: ImpactStyle.Light })
this.stopRecording();
}
@@ -141,51 +141,51 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
longpress.enable();
}
calculateDuration(){
if(!this.recording){
calculateDuration() {
if (!this.recording) {
this.duration = 0;
this.durationDisplay = '';
return;
}
this.duration += 1;
const minutes = Math.floor(this.duration / 60);
const seconds = (this.duration % 60).toString().padStart(2,'0');
const seconds = (this.duration % 60).toString().padStart(2, '0');
this.durationDisplay = `${minutes}:${seconds}`;
setTimeout(()=>{
setTimeout(() => {
this.calculateDuration();
}, 1000)
}
async loadFiles(){
async loadFiles() {
Filesystem.readdir({
path: '',
directory: Directory.Data
}).then(result =>{
}).then(result => {
console.log(result);
const temp:any[] = result.files.reverse();
const temp: any[] = result.files.reverse();
this.storedFileNames = temp[0];
console.log(this.storedFileNames);
})
}
startRecording(){
if(this.recording){
startRecording() {
if (this.recording) {
return;
}
this.recording = true;
VoiceRecorder.startRecording();
}
stopRecording(){
if(!this.recording){
stopRecording() {
if (!this.recording) {
return;
}
this.recording = false;
VoiceRecorder.stopRecording().then(async (result: RecordingData) =>{
VoiceRecorder.stopRecording().then(async (result: RecordingData) => {
this.recording = false;
if(result.value && result.value.recordDataBase64){
if (result.value && result.value.recordDataBase64) {
const recordData = result.value.recordDataBase64;
console.log(recordData);
this.myAudio = recordData;
@@ -200,7 +200,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
async playFile(fileName?:any){
async playFile(fileName?: any) {
const audioFile = await Filesystem.readFile({
path: fileName,
directory: Directory.Data
@@ -214,33 +214,33 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
handlePress(id?:string){
handlePress(id?: string) {
this.selectedMsgId = id;
this.showMessageOptions = true;
}
handleClick(){
handleClick() {
this.showMessageOptions = false;
this.selectedMsgId = "";
}
deleteMessage(msgId:string){
deleteMessage(msgId: string) {
let body = {
"roomId": this.roomId,
"msgId": msgId,
"asUser": false,
}
if(msgId){
if (msgId) {
this.alertService.confirmDeleteMessage(body);
}
else{
else {
this.toastService.badRequest('Não foi possível apagar');
}
this.showMessageOptions = false;
this.selectedMsgId = "";
}
setStatus(status:string){
setStatus(status: string) {
let body = {
message: '',
status: status,
@@ -250,37 +250,37 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
})
}
notImplemented(){
notImplemented() {
this.alertService.presentAlert('Funcionalidade em desenvolvimento');
}
close(){
close() {
this.modalController.dismiss();
}
load(){
load() {
this.serverLongPull();
this.getChatMembers();
}
doRefresh(ev:any){
doRefresh(ev: any) {
this.load();
ev.target.complete();
}
scrollToBottom(): void {
try {
if(this.scrollingOnce){
if (this.scrollingOnce) {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
//this.scrollingOnce = false;
}
} catch(err) { }
} catch (err) { }
}
scrollToBottomClicked(): void {
try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch(err) { }
} catch (err) { }
}
@@ -297,10 +297,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
//alert('UP');
this.scrollingOnce = false;
}
if((containerHeight - 100) > scroll){
if ((containerHeight - 100) > scroll) {
this.scrollToBottomBtn = true;
}
else{
else {
this.scrollToBottomBtn = false;
}
this.currentPosition = scroll;
@@ -320,7 +320,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
"rid": this.roomId, "msg": this.message
}
}
this.chatService.sendMessage(body).subscribe(res=> {
this.chatService.sendMessage(body).subscribe(res => {
//this.loadMessages();
this.scrollingOnce = true;
});
@@ -340,23 +340,23 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
})
}
viewDocument(file:any, url?:string){
viewDocument(file: any, url?: string) {
console.log(file);
if(file.type == "application/webtrix") {
if (file.type == "application/webtrix") {
this.openViewDocumentModal(file);
}
else{
else {
let fullUrl = "https://www.tabularium.pt" + url;
this.fileService.viewDocumentByUrl(fullUrl);
}
}
docIndex(index: number){
docIndex(index: number) {
this.dicIndex = index
}
async openViewDocumentModal(file:any){
async openViewDocumentModal(file: any) {
let task = {
serialNumber: '',
@@ -373,17 +373,17 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
let doc = {
"Id": "",
"ParentId": "",
"Source": 1,
"ApplicationId": file.ApplicationId,
"CreateDate": "",
"Data": null,
"Description":"",
"Link": null,
"SourceId": file.DocId,
"SourceName": file.Assunto,
"Stakeholders": "",
"Id": "",
"ParentId": "",
"Source": 1,
"ApplicationId": file.ApplicationId,
"CreateDate": "",
"Data": null,
"Description": "",
"Link": null,
"SourceId": file.DocId,
"SourceName": file.Assunto,
"Stakeholders": "",
}
const modal = await this.modalController.create({
@@ -408,7 +408,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
getChatMembers() {
this.showLoader = true;
this.chatService.getMembers(this.roomId).subscribe(res=> {
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);
@@ -417,32 +417,32 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
});
}
showDateDuration(start:any){
showDateDuration(start: any) {
let end;
end = new Date();
start = new Date(start);
let customizedDate;
const totalSeconds = Math.floor((end - (start))/1000);;
const totalMinutes = Math.floor(totalSeconds/60);
const totalHours = Math.floor(totalMinutes/60);
const totalDays = Math.floor(totalHours/24);
const totalSeconds = Math.floor((end - (start)) / 1000);;
const totalMinutes = Math.floor(totalSeconds / 60);
const totalHours = Math.floor(totalMinutes / 60);
const totalDays = Math.floor(totalHours / 24);
const hours = totalHours - ( totalDays * 24 );
const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );
const hours = totalHours - (totalDays * 24);
const minutes = totalMinutes - (totalDays * 24 * 60) - (hours * 60);
const seconds = totalSeconds - (totalDays * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);
if(totalDays == 0){
if(start.getDate() == new Date().getDate()){
if (totalDays == 0) {
if (start.getDate() == new Date().getDate()) {
let time = start.getHours() + ":" + this.addZero(start.getUTCMinutes());
return time;
}
else{
else {
return 'Ontem';
}
}
else{
let date = start.getDate() + "/" + (start.getMonth()+1) + "/" + start.getFullYear();
else {
let date = start.getDate() + "/" + (start.getMonth() + 1) + "/" + start.getFullYear();
return date;
}
}
@@ -467,7 +467,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
return await popover.present();
}
async addContacts(){
async addContacts() {
const modal = await this.modalController.create({
component: ContactsPage,
componentProps: {},
@@ -481,19 +481,19 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
async bookMeeting() {
this.attendees = this.members.map((val)=>{
this.attendees = this.members.map((val) => {
return {
Name: val.name,
EmailAddress: val.username+"@"+environment.domain,
EmailAddress: val.username + "@" + environment.domain,
IsRequired: "true",
}
});
console.log(this.attendees);
this.popoverController.dismiss();
if( window.innerWidth <= 1024){
if (window.innerWidth <= 1024) {
const modal = await this.modalController.create({
component: NewEventPage,
componentProps:{
componentProps: {
attendees: this.attendees,
},
cssClass: 'modal modal-desktop',
@@ -501,7 +501,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
});
await modal.present();
modal.onDidDismiss().then((data) => {
if(data){
if (data) {
}
});
@@ -524,24 +524,24 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
translucent: true
});
await popover.present();
popover.onDidDismiss().then((res)=>{
popover.onDidDismiss().then((res) => {
console.log(res['data']);
if(res['data'] == 'meeting'){
if (res['data'] == 'meeting') {
this.bookMeeting();
}
else if(res['data'] == 'take-picture'){
else if (res['data'] == 'take-picture') {
this.fileService.addCameraPictureToChat(roomId);
//this.loadPicture();
}
else if(res['data'] == 'add-picture'){
else if (res['data'] == 'add-picture') {
this.fileService.addPictureToChatMobile(roomId);
//this.loadPicture();
}
else if(res['data'] == 'add-document'){
else if (res['data'] == 'add-document') {
this.fileService.addDocumentToChat(this.roomId);
//this.loadDocument();
}
else if(res['data'] == 'documentoGestaoDocumental'){
else if (res['data'] == 'documentoGestaoDocumental') {
this.fileService.addDocGestaoDocumentalToChat(this.roomId);
//this.addDocGestaoDocumental();
@@ -558,19 +558,19 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
let chatmsgArray = [];
let array = []
msg.forEach(element => {
console.log('CHANNEL ELEMENT',element.channels)
console.log('CHANNEL ELEMENT', element.channels)
let msgChat = {
_id: element.Id,
attachments: this.isJson(element.Attachments),
channels: this.isJson(element.Channels),
file: this.isJson(element.File),
mentions: this.isJson(element.Mentions),
msg: element.Msg,
rid: element.Rid,
ts: element.Ts,
u: this.isJson(element.U),
_updatedAt: element.UpdatedAt
_id: element.Id,
attachments: this.isJson(element.Attachments),
channels: this.isJson(element.Channels),
file: this.isJson(element.File),
mentions: this.isJson(element.Mentions),
msg: element.Msg,
rid: element.Rid,
ts: element.Ts,
u: this.isJson(element.U),
_updatedAt: element.UpdatedAt
}
chatmsgArray.push(msgChat)
@@ -584,12 +584,12 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
isJson(str) {
try {
JSON.parse(str);
JSON.parse(str);
} catch (e) {
return "";
return "";
}
return JSON.parse(str);
}
}
@@ -613,7 +613,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.sqlservice.addChatMSG(chatmsg)
});
}
}
async serverLongPull() {
@@ -627,44 +627,47 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.chatService.getRoomMessages(roomId).subscribe(async res => {
console.log("Chat message",res)
console.log("Chat message", res)
this.transformDataMSG(res['messages'])
this.transformDataMSG(res['messages'])
this.getRoomMessageDB(this.roomId);
if (res == 502) {
// Connection timeout
// happens when the synchro was pending for too long
// let's reconnect
await this.serverLongPull();
}
else if (res != 200) {
// Show Error
//showMessage(response.statusText);
//this.loadMessages()
//this.messages = res['messages'].reverse();
//this.chatMessageStore.add(roomId, this.messages)
//console.log(this.messages);
// Reconnect in one second
if(this.route.url != "/home/chat"){
console.log("Timer message stop")
} else {
//Check if modal is opened
if(document.querySelector('.isMessagesChatOpened')){
await new Promise(resolve => setTimeout(resolve, 5000));
await this.serverLongPull();
//console.log('Timer message running')
}
if (res == 502) {
// Connection timeout
// happens when the synchro was pending for too long
// let's reconnect
await this.serverLongPull();
}
else if (res != 200) {
// Show Error
//showMessage(response.statusText);
//this.loadMessages()
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.messages = res['messages'].reverse();
this.chatMessageStore.add(roomId, this.messages)
}
} else {
// Got message
//let message = await response.text();
//this.loadMessages()
await this.serverLongPull();
}
//console.log(this.messages);
// Reconnect in one second
if (this.route.url != "/home/chat") {
console.log("Timer message stop")
} else {
//Check if modal is opened
if (document.querySelector('.isMessagesChatOpened')) {
await new Promise(resolve => setTimeout(resolve, 5000));
await this.serverLongPull();
//console.log('Timer message running')
}
}
} else {
// Got message
//let message = await response.text();
//this.loadMessages()
await this.serverLongPull();
}
});
}
@@ -676,45 +679,45 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
centeredSlides: true
};
zoomActive = false;
zoomScale = 1;
zoomScale = 1;
sliderZoomOpts = {
allowSlidePrev: false,
allowSlideNext: false,
zoom: {
maxRatio: 5
},
on: {
zoomChange: (scale, imageEl, slideEl) => {
this.zoomActive = true;
this.zoomScale = scale/5;
this.changeDetectorRef.detectChanges();
sliderZoomOpts = {
allowSlidePrev: false,
allowSlideNext: false,
zoom: {
maxRatio: 5
},
on: {
zoomChange: (scale, imageEl, slideEl) => {
this.zoomActive = true;
this.zoomScale = scale / 5;
this.changeDetectorRef.detectChanges();
}
}
}
}
async touchEnd(zoomslides: IonSlides, card) {
// Zoom back to normal
const slider = await zoomslides.getSwiper();
const zoom = slider.zoom;
zoom.out();
async touchEnd(zoomslides: IonSlides, card) {
// Zoom back to normal
const slider = await zoomslides.getSwiper();
const zoom = slider.zoom;
zoom.out();
// Card back to normal
card.el.style['z-index'] = 9;
// Card back to normal
card.el.style['z-index'] = 9;
this.zoomActive = false;
this.changeDetectorRef.detectChanges();
}
this.zoomActive = false;
this.changeDetectorRef.detectChanges();
}
touchStart(card) {
// Make card appear above backdrop
card.el.style['z-index'] = 11;
}
touchStart(card) {
// Make card appear above backdrop
card.el.style['z-index'] = 11;
}
async openPreview(msg) {
const modal = await this.modalController.create({
component: ViewMediaPage,
component: ViewMediaPage,
cssClass: 'modal modal-desktop',
componentProps: {
image: msg.attachments[0].image_url,
@@ -726,22 +729,22 @@ touchStart(card) {
}
imageSize(img){
imageSize(img) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width=300
canvas.height=234
canvas.width = 300
canvas.height = 234
ctx.drawImage(img.attachments[0].image_url, 0, 0, 300, 234);
document.body.appendChild(canvas);
}
}
getPicture(img){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width=300
canvas.height=234
ctx.drawImage(img.attachments[0].image_url, 0, 0, 300, 234);
document.body.appendChild(canvas);
getPicture(img) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 300
canvas.height = 234
ctx.drawImage(img.attachments[0].image_url, 0, 0, 300, 234);
document.body.appendChild(canvas);
}