From 796143d7c4ab555f91baff80d20f8416479fc919 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Wed, 8 Dec 2021 22:49:14 +0100 Subject: [PATCH 1/2] bug fix afaster adding sqlite to chat stop presenting msg on web --- src/app/pages/chat/chat.page.ts | 18 +- src/app/pages/chat/messages/messages.page.ts | 345 ++++++++++--------- 2 files changed, 187 insertions(+), 176 deletions(-) diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index 4921e409b..ef5429eb6 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -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); + } + }); } diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index b5295fc19..fa191d63d 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -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); } From af84d4ed6e5abf33abcd09318d98c0737b14c7aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Sat, 18 Dec 2021 16:58:53 +0100 Subject: [PATCH 2/2] Bug presenting chat rooms --- src/app/pages/chat/chat.page.ts | 192 ++++++++++++++++++++++++++--- src/app/services/sqlite.service.ts | 8 +- 2 files changed, 182 insertions(+), 18 deletions(-) diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index 07ec3db6f..61c5b9e89 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -30,6 +30,7 @@ import { TimeService } from 'src/app/services/functions/time.service'; import { ThemeService } from 'src/app/services/theme.service' import { DataService } from 'src/app/services/data.service'; import { SqliteService } from 'src/app/services/sqlite.service'; +import { StorageService } from 'src/app/services/storage.service'; @@ -121,7 +122,8 @@ export class ChatPage implements OnInit { private dataService: DataService, private router: Router, private sqlservice: SqliteService, - private platform: Platform + private platform: Platform, + private storageservice: StorageService ) { this.loggedUserChat = authService.ValidatedUserChat['data']; @@ -404,20 +406,39 @@ export class ChatPage implements OnInit { }); } + getDirectMessagesDB() { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storageservice.get("rooms").then((rooms) =>{ + + this.userDirectMessages = rooms.sort((a, b) => { + var dateA = new Date(a._updatedAt).getTime(); + var dateB = new Date(b._updatedAt).getTime(); + return dateB - dateA; + }); + console.log('DIRECTMESSAGE FROM DB', this.userDirectMessages); + + console.log('ROOMS FROM DB', rooms) + }) + + this.storageservice.get('chatusers').then((users) => { + this.dmUsers = users.filter(data => data.username != this.loggedUserChat.me.username); + }) } else { this.sqlservice.getAllChatRoom().then((rooms: any) => { + console.log('ROOMS FROM DB', rooms) let roomsArray = []; rooms.forEach(element => { let roomListDB = { _id: element.Id, - uids: JSON.parse(element.Uids), - usernames: JSON.parse(element.Usernames), - lastMessage: JSON.parse(element.LastMessage), + uids: this.isJson(element.Uids), + usernames: this.isJson(element.Usernames), + lastMessage: this.isJson(element.LastMessage), _updatedAt: element.UpdatedAt } - roomsArray.push(roomListDB) + if(element.customFields == "undefined") { + roomsArray.push(roomListDB) + } }); this.userDirectMessages = roomsArray.sort((a, b) => { @@ -452,6 +473,22 @@ export class ChatPage implements OnInit { transformDataRoomList(data) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + let roomsArray = []; + data.forEach(element => { + let roomList = { + _id: element._id, + uids: element.uids, + usernames: element.usernames, + lastMessage: element.lastMessage, + _updatedAt: element._updatedAt + } + + console.log(' Web TRANSFORM ROOM LIST', roomList) + roomsArray.push(roomList) + }); + + this.storageservice.store('rooms', roomsArray); + } else { data.forEach(element => { let roomList = { @@ -470,6 +507,18 @@ export class ChatPage implements OnInit { transformDataUserList(users) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + let usersArray = []; + users.forEach(element => { + console.log('TRANSFORM USER CHAT 1', element) + let chatusers = { + _id: element._id, + name: element.name, + username: element.username + } + console.log('TRANSFORM USER CHAT 2', chatusers) + usersArray.push(chatusers); + }); + this.storageservice.store('chatusers',usersArray); } else { users.forEach(element => { console.log('TRANSFORM USER CHAT 1', element) @@ -496,13 +545,13 @@ export class ChatPage implements OnInit { console.log('Chat list', res); if (res != 200) { - if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + /* 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); @@ -552,20 +601,124 @@ export class ChatPage implements OnInit { }); } + getGroupsDB() { + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storageservice.get("grouprooms").then((rooms) =>{ + + + this.allGroups = rooms.sort((a, b) => { + var dateA = new Date(a._updatedAt).getTime(); + var dateB = new Date(b._updatedAt).getTime(); + return dateB - dateA; + }); + + console.log('GROUPS FROM DB', this.allGroups) + }) + + this.storageservice.get('chatusers').then((users) => { + this.dmUsers = users.filter(data => data.username != this.loggedUserChat.me.username); + }) + } else { + this.sqlservice.getAllChatRoom().then((rooms: any) => { + + let roomsArray = []; + rooms.forEach(element => { + let fddf = this.isJson(element.LastMessage); + let roomListDB = { + _id: element.Id, + customFields: this.isJson(element.customFields), + name: element.name, + lastMessage: this.isJson(element.LastMessage), + _updatedAt: element.UpdatedAt + } + if(element.customFields != "undefined") { + roomsArray.push(roomListDB) + } + }); + + this.allGroups = roomsArray.sort((a, b) => { + var dateA = new Date(a._updatedAt).getTime(); + var dateB = new Date(b._updatedAt).getTime(); + return dateB - dateA; + }); + console.log('Group FROM DB', this.allGroups); + + }) + + /* this.sqlservice.getAllChatUsers().then((userslist: any) => { + console.log('USERS FOM DB 1', userslist) + let chatusersArray = []; + userslist.forEach(element => { + console.log('USERS FOM DB 2', element) + let userListDB = { + _id: element.Id, + name: element.Name, + username: element.Username + } + + chatusersArray.push(userListDB); + }); + + this.dmUsers = chatusersArray.filter(data => data.username != this.loggedUserChat.me.username); + + }) */ + } + + } + + transformGroups(data) { + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + let groupsArray = []; + data.forEach(element => { + let roomList = { + _id: element._id, + uids: element.uids, + usernames: element.usernames, + name: element.name, + customFields: element.customFields, + lastMessage: element.lastMessage, + _updatedAt: element._updatedAt + } + + console.log(' Web TRANSFORM ROOM LIST', roomList) + groupsArray.push(roomList) + }); + + this.storageservice.store('grouprooms', groupsArray); + + } else { + data.forEach(element => { + let roomList = { + id: element._id, + uids: element.uids, + usernames: element.usernames, + customFields: element.customFields, + name: element.name, + lastMessage: element.lastMessage, + updatedat: element._updatedAt + } + + console.log('TRANSFORM ROOM LIST', roomList) + this.sqlservice.addChatListRoom(roomList); + }); + } + + } + async getGroups(event?) { this.result = this.chatService.getAllPrivateGroups().subscribe(async (res: any) => { //console.log(res); if (res.groups != 200) { + this.transformGroups(res.groups); + this.getGroupsDB(); + + /* this.privateGroups = res.groups; + this.transformGroups(res.groups); + this.getGroupsDB(); + this.privateGroups = res.groups; - /* this.result = this.chatService.getAllUserChannels().subscribe((res:any)=>{ - this.publicGroups = res.channels; */ - //let all = this.privateGroups.concat(this.publicGroups); - this.allGroups = this.privateGroups.sort((a, b) => { - var dateA = new Date(a._updatedAt).getTime(); - var dateB = new Date(b._updatedAt).getTime(); - return dateB - dateA; - }); + console.log('Chat list group' , res); */ //console.log(this.allGroups); /* }); */ if (this.route.url != "/home/chat") { @@ -588,6 +741,15 @@ export class ChatPage implements OnInit { }); } + isJson(str) { + try { + JSON.parse(str); + } catch (e) { + return str; + } + return JSON.parse(str); + } + async selectContact() { const modal = await this.modalController.create({ component: ContactsPage, diff --git a/src/app/services/sqlite.service.ts b/src/app/services/sqlite.service.ts index ce10d1711..3a557a4fc 100644 --- a/src/app/services/sqlite.service.ts +++ b/src/app/services/sqlite.service.ts @@ -140,7 +140,9 @@ export class SqliteService { Uids Text, Usernames Text, LastMessage Text, - UpdatedAt varchar(255) + UpdatedAt varchar(255), + customFields Text, + name varchar(255) )`, []) .then((res) => { console.log("Sucess chat list room Table created: ", res) @@ -248,8 +250,8 @@ export class SqliteService { public addChatListRoom(data) { console.log('INSIDE DB CHAT LIST ROOM',data,) this.dbInstance.executeSql(` - INSERT OR REPLACE INTO ${this.chatlistroom} (Id,Uids,Usernames,LastMessage,UpdatedAt) - VALUES ('${data.id}','${JSON.stringify(data.uids)}','${JSON.stringify(data.usernames)}','${JSON.stringify(data.lastMessage)}','${data.updatedat}')`, []) + INSERT OR REPLACE INTO ${this.chatlistroom} (Id,Uids,Usernames,LastMessage,UpdatedAt,customFields,name) + VALUES ('${data.id}','${JSON.stringify(data.uids)}','${JSON.stringify(data.usernames)}','${JSON.stringify(data.lastMessage)}','${data.updatedat}','${JSON.stringify(data.customFields)}','${data.name}')`, []) .then(() => { console.log("chat room add with Success");