diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index 879f56f13..d77448c51 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -9,7 +9,7 @@ import { ComponentFactory, Output } from '@angular/core'; -import { ModalController } from '@ionic/angular'; +import { ModalController, Platform } from '@ionic/angular'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { GroupMessagesPage } from './group-messages/group-messages.page'; @@ -30,6 +30,7 @@ import { environment } from 'src/environments/environment'; 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'; @@ -43,13 +44,13 @@ export class ChatPage implements OnInit { showLoader: boolean; headers: HttpHeaders; - options:any; - X_User_Id:any; - X_Auth_Token:any; + options: any; + X_User_Id: any; + X_Auth_Token: any; loggedUser: any; /* Set segment variable */ - segment:string; + segment: string; allGroups: any[]; privateGroups: any[]; publicGroups: any[]; @@ -57,8 +58,8 @@ export class ChatPage implements OnInit { userRooms: any[]; userChannels: any[]; userDirectMessages: any[]; - result:any; - dmUsers:any[] = []; + result: any; + dmUsers: any[] = []; idSelected: string; desktopComponent: any = { @@ -70,17 +71,17 @@ export class ChatPage implements OnInit { //@ViewChild('groupMessages') child:GroupMessagesPage; componentRef: any; - roomId:any; - groupRoomId:any; - showEmptyComponent=true; - showMessages=false; - showContacts=false; - showNewGroup=false; - showEditGroup=false; - showGroupMessages=false; - showGroupContacts=false; - showNewEvent=false; - showAttendees=false; + roomId: any; + groupRoomId: any; + showEmptyComponent = true; + showMessages = false; + showContacts = false; + showNewGroup = false; + showEditGroup = false; + showGroupMessages = false; + showGroupContacts = false; + showNewEvent = false; + showAttendees = false; emptyTextDescription = 'Sem conversa selecionada'; @Output() getRoomInfo; @@ -97,169 +98,171 @@ export class ChatPage implements OnInit { /* Fim websockets variables*/ - loggedUserChat:any; + loggedUserChat: any; hideRefreshBtn = true; taskParticipants: any = []; taskParticipantsCc: any = []; adding: "intervenient" | "CC" = "intervenient"; - profile:'mdgpr' | 'pr'; + profile: 'mdgpr' | 'pr'; eventSelectedDate: Date = new Date(); - contacts: EventPerson[]; - showEventEditOrOpen: "edit" | "add" | "" | "eventoToApprove" = "" + contacts: EventPerson[]; + showEventEditOrOpen: "edit" | "add" | "" | "eventoToApprove" = "" constructor( - private http:HttpClient, + private http: HttpClient, private chatService: ChatService, private modalController: ModalController, private authService: AuthService, - private storage:Storage, + private storage: Storage, private resolver: ComponentFactoryResolver, private route: Router, private timeService: TimeService, public ThemeService: ThemeService, - private dataService:DataService, + private dataService: DataService, private router: Router, - - ){ - this.loggedUserChat = authService.ValidatedUserChat['data']; - this.headers = new HttpHeaders(); - window.onresize = (event) => { - if( window.innerWidth > 701){ - this.modalController.dismiss(); - } - }; + private sqlservice: SqliteService, + private platform: Platform - } + ) { + this.loggedUserChat = authService.ValidatedUserChat['data']; + this.headers = new HttpHeaders(); + window.onresize = (event) => { + if (window.innerWidth > 701) { + this.modalController.dismiss(); + } + }; + + } ngOnInit() { console.log(this.loggedUserChat); this.segment = "Contactos"; - this.authService.userData$.subscribe((res:any)=>{ - this.loggedUser=res; + this.authService.userData$.subscribe((res: any) => { + this.loggedUser = res; console.log(this.loggedUser); this.load(); }); - /* websocket functions */ - //this.sendMsg(); + /* websocket functions */ + //this.sendMsg(); - /* Fim websocket functions */ - this.hideRefreshButton(); - this.getChatMembers(); + /* Fim websocket functions */ + this.hideRefreshButton(); + this.getChatMembers(); - //Teste - let t = this.showDateDuration(new Date()); - console.log(t); + //Teste + let t = this.showDateDuration(new Date()); + console.log(t); - this.setStatus('away'); - if(this.dataService.get("newGroup")){ - this.openNewGroupPage(); + this.setStatus('away'); + if (this.dataService.get("newGroup")) { + this.openNewGroupPage(); + } + + this.router.events.forEach((event) => { + if (event instanceof NavigationStart && event.url.startsWith('/home/chat')) { + if (window.location.pathname.split('/').length >= 4 && window.location.pathname.startsWith('/home/chat')) { + alert('OIII') + } else { + if (this.dataService.get("newGroup")) { + this.openNewGroupPage(); + } + } + } + }); } - this.router.events.forEach((event) => { - if (event instanceof NavigationStart && event.url.startsWith('/home/chat')) { - if (window.location.pathname.split('/').length >= 4 && window.location.pathname.startsWith('/home/chat')) { - alert('OIII') - } else { - if(this.dataService.get("newGroup")){ - this.openNewGroupPage(); + ngOnDestroy() { + this.setStatus('offline'); + console.log('On Destroy') + } + + setStatus(status: string) { + let body = { + message: '', + status: status, + } + this.chatService.setUserStatus(body).subscribe(res => { + console.log(res); + }) + } + + hideRefreshButton() { + window.onresize = (event) => { + if (window.innerWidth < 701) { + this.idSelected = ''; + this.hideRefreshBtn = false; + } + else { + this.hideRefreshBtn = true; + if (this.idSelected == '') { + this.showEmptyComponent = true; } } } - }); -} - -ngOnDestroy(){ - this.setStatus('offline'); - console.log('On Destroy') -} - -setStatus(status:string){ - let body = { - message: '', - status: status, - } - this.chatService.setUserStatus(body).subscribe(res => { - console.log(res); - }) -} - -hideRefreshButton(){ - window.onresize = (event) => { - if( window.innerWidth < 701) { + if (window.innerWidth < 701) { this.idSelected = ''; this.hideRefreshBtn = false; } - else{ - this.hideRefreshBtn = true; - if(this.idSelected == ''){ - this.showEmptyComponent=true; - } - } } - if(window.innerWidth < 701){ - this.idSelected = ''; - this.hideRefreshBtn = false; - } -} -/* loadMessage(){ - this.chatService.messages.subscribe(msg => { - console.log("Response from websocket: " + msg); - }); -} */ -/* sendMsg() { - console.log("new message from client to websocket: ", this.message); - this.chatService.messages.next(this.message); - this.message.msg = ""; -} */ + /* loadMessage(){ + this.chatService.messages.subscribe(msg => { + console.log("Response from websocket: " + msg); + }); + } */ + /* sendMsg() { + console.log("new message from client to websocket: ", this.message); + this.chatService.messages.next(this.message); + this.message.msg = ""; + } */ /* Fim websockets functions */ closeAllDesktopComponents() { - this.showMessages=false; - this.showContacts=false; - this.showNewGroup=false; - this.showEditGroup=false; - this.showGroupMessages=false; - this.showEmptyComponent=false; - this.showGroupContacts=false; - this.showNewEvent=false; - this.showAttendees=false; + this.showMessages = false; + this.showContacts = false; + this.showNewGroup = false; + this.showEditGroup = false; + this.showGroupMessages = false; + this.showEmptyComponent = false; + this.showGroupContacts = false; + this.showNewEvent = false; + this.showAttendees = false; console.log('All components closed!'); } - showEmptyContainer(){ + showEmptyContainer() { this.idSelected = ''; - this.showEmptyComponent=true; + this.showEmptyComponent = true; } - openGroupContactsPage(data){ + openGroupContactsPage(data) { this.idSelected = ''; this.groupRoomId = data; this.closeAllDesktopComponents(); - if(window.innerWidth < 801){ + if (window.innerWidth < 801) { } - else{ + else { this.showGroupContacts = true; } } openMessagesPage(rid) { - if( window.innerWidth < 701){ + if (window.innerWidth < 701) { this.openMessagesModal(rid); //this.router.navigate(['/home/chat/messages',rid,]); } - else{ + else { this.idSelected = rid; this.closeAllDesktopComponents(); this.showEmptyComponent = false; this.roomId = rid; - this.showMessages=true; + this.showMessages = true; } } openContactsPage() { @@ -267,63 +270,63 @@ hideRefreshButton(){ this.idSelected = ''; this.closeAllDesktopComponents(); - if( window.innerWidth < 701){ + if (window.innerWidth < 701) { this.selectContact(); } - else{ + else { console.log('here'); - this.showContacts=true; + this.showContacts = true; } } openNewGroupPage() { this.idSelected = ''; - if( window.innerWidth < 801){ + if (window.innerWidth < 801) { this.newGroup(); } - else{ + else { this.closeAllDesktopComponents(); - this.showNewGroup=true; + this.showNewGroup = true; } } openEditGroupPage(rid) { - if( window.innerWidth < 801){ + if (window.innerWidth < 801) { this.editGroup(rid); } - else{ + else { this.closeAllDesktopComponents(); - this.showEditGroup=true; + this.showEditGroup = true; } } openGroupMessagesPage(rid) { - if( window.innerWidth < 701){ + if (window.innerWidth < 701) { this.openGroupMessagesModal(rid); } - else{ + else { this.idSelected = rid; this.closeAllDesktopComponents(); this.showEmptyComponent = false; this.roomId = rid; console.log(this.roomId); - this.showGroupMessages=true; + this.showGroupMessages = true; } } - openNewEventPage(data:any){ - this.taskParticipants = data.members.map((val) =>{ + openNewEventPage(data: any) { + this.taskParticipants = data.members.map((val) => { return { Name: val.name, - EmailAddress: val.username+"@"+environment.domain, + EmailAddress: val.username + "@" + environment.domain, IsRequired: "true", } }); this.closeAllDesktopComponents(); - if(window.innerWidth < 701){ + if (window.innerWidth < 701) { console.log('Mobile'); } - else{ - this.showNewEvent=true; + else { + this.showNewEvent = true; } } @@ -337,7 +340,7 @@ hideRefreshButton(){ this.contacts = []; } - async setContact(data:EventPerson[]) { + async setContact(data: EventPerson[]) { this.contacts = data; } @@ -352,7 +355,7 @@ hideRefreshButton(){ async closeAttendeesComponent() { this.closeAllDesktopComponents(); - this.showNewEvent = true; + this.showNewEvent = true; } async closeNewEventComponent() { @@ -361,24 +364,23 @@ hideRefreshButton(){ this.idSelected = ""; } - onSegmentChange(){ + onSegmentChange() { this.load(); } - doRefresh(event){ + doRefresh(event) { setTimeout(() => { this.load(); event.target.complete(); }, 1000); } - refreshing(){ + refreshing() { this.load(); } - load(){ - switch (this.segment) - { + load() { + switch (this.segment) { case "Contactos": this.getDirectMessages(); break; @@ -388,106 +390,193 @@ hideRefreshButton(){ break; } } - customRoom(){ + customRoom() { let params = new HttpParams(); params = params.set("types", "c"); - this.chatService.customsRooms(params).subscribe(res=>{ + this.chatService.customsRooms(params).subscribe(res => { console.log(res); }); } - async getDirectMessages(event?){ + getDirectMessagesDB() { + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + } else { + this.sqlservice.getAllChatRoom().then((rooms: any) => { + 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), + _updatedAt: element.UpdatedAt + } + roomsArray.push(roomListDB) + }); - this.chatService.getAllDirectMessages().subscribe(async (res:any)=>{ - //console.log(res.ims); - - if(res != 200){ - //console.log(res.ims); - this.userDirectMessages = res.ims.sort((a,b)=>{ + this.userDirectMessages = roomsArray.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.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); + + }) + } + } + + transformDataRoomList(data) { + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + } else { + data.forEach(element => { + let roomList = { + id: element._id, + uids: element.uids, + usernames: element.usernames, + lastMessage: element.lastMessage, + updatedat: element._updatedAt + } + + console.log('TRANSFORM ROOM LIST',roomList ) + this.sqlservice.addChatListRoom(roomList); + }); + } + } + + transformDataUserList(users) { + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + } else { + 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) + this.sqlservice.addChatListUsers(chatusers); + }); + } + } + + async getDirectMessages(event?) { + + this.chatService.getAllDirectMessages().subscribe(async (res: any) => { + + + this.transformDataRoomList(res.ims) + + this.getDirectMessagesDB() + + console.log('Chat list', res); + + if (res != 200) { + //console.log(res.ims); + /* 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(this.userDirectMessages); - if(this.route.url != "/home/chat"){ + if (this.route.url != "/home/chat") { //console.log("Timer message stop") } else { //console.log('TIMER'); //Check if modal is opened - if(this.segment == "Contactos" && this.showMessages != true){ + if (this.segment == "Contactos" && this.showMessages != true) { await new Promise(resolve => setTimeout(resolve, 1000)); await this.getDirectMessages(); //console.log('Timer contactos list running') } - else{ + else { //console.log('No timer!'); } } } - else{ + else { await this.getDirectMessages(); } }); } - showDateDuration(start:any){ + showDateDuration(start: any) { return this.timeService.showDateDuration(start); } - countDownDate(date:any, roomId:string){ + countDownDate(date: any, roomId: string) { return this.timeService.countDownDate(date, roomId); } - async getChatMembers(){ + async getChatMembers() { //return await this.chatService.getMembers(roomId).toPromise(); - this.chatService.getAllUsers().subscribe(res=> { - console.log(res); + this.chatService.getAllUsers().subscribe(res => { + console.log('chatusers', res); + this.transformDataUserList(res['users']) - this.dmUsers = res['users'].filter(data => data.username != this.loggedUserChat.me.username); - console.log(this.dmUsers); + //this.dmUsers = res['users'].filter(data => data.username != this.loggedUserChat.me.username); + //console.log(this.dmUsers); }); } - async getGroups(event?){ - this.result = this.chatService.getAllPrivateGroups().subscribe(async (res:any)=>{ + async getGroups(event?) { + this.result = this.chatService.getAllPrivateGroups().subscribe(async (res: any) => { //console.log(res); - if(res.groups != 200){ + if (res.groups != 200) { - this.privateGroups = res.groups; - /* this.result = this.chatService.getAllUserChannels().subscribe((res:any)=>{ - this.publicGroups = res.channels; */ + 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)=>{ + 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(this.allGroups); - /* }); */ - if(this.route.url != "/home/chat"){ - console.log("Timer message stop") + /* }); */ + if (this.route.url != "/home/chat") { + console.log("Timer message stop") + } + else { + //Check if modal is opened + if (this.segment == "Grupos" && this.showGroupMessages != true) { + await new Promise(resolve => setTimeout(resolve, 1000)); + await this.getGroups(); + //console.log('Timer groups list running') + } + } + } else { - //Check if modal is opened - if(this.segment == "Grupos" && this.showGroupMessages != true){ - await new Promise(resolve => setTimeout(resolve, 1000)); - await this.getGroups(); - //console.log('Timer groups list running') - } + await this.getGroups(); } - } - else{ - await this.getGroups(); - } - }); } - async selectContact(){ + async selectContact() { const modal = await this.modalController.create({ component: ContactsPage, cssClass: 'modal modal-desktop', @@ -496,7 +585,7 @@ hideRefreshButton(){ modal.onDidDismiss(); } - async newGroup(){ + async newGroup() { const modal = await this.modalController.create({ component: NewGroupPage, cssClass: 'modal modal-desktop', @@ -505,7 +594,7 @@ hideRefreshButton(){ modal.onDidDismiss(); } - async editGroup(roomId){ + async editGroup(roomId) { const modal = await this.modalController.create({ component: EditGroupPage, cssClass: 'modal modal-desktop', @@ -514,13 +603,13 @@ hideRefreshButton(){ }, }); await modal.present(); - modal.onDidDismiss().then((res)=>{ + modal.onDidDismiss().then((res) => { console.log(res.data); this.modalController.dismiss(res.data); }); } - async openMessagesModal(roomId:any){ + async openMessagesModal(roomId: any) { this.closeAllDesktopComponents(); console.log(roomId); @@ -536,7 +625,7 @@ hideRefreshButton(){ modal.onDidDismiss(); } - async openGroupMessagesModal(roomId:any){ + async openGroupMessagesModal(roomId: any) { console.log(roomId); @@ -551,10 +640,10 @@ hideRefreshButton(){ modal.onDidDismiss(); } -// this.crop.crop('path/to/image.jpg', {quality: 75}) -// .then( -// newImage => console.log('new image path is: ' + newImage), -// error => console.error('Error cropping image', error) -// ); + // this.crop.crop('path/to/image.jpg', {quality: 75}) + // .then( + // newImage => console.log('new image path is: ' + newImage), + // error => console.error('Error cropping image', error) + // ); - } +} diff --git a/src/app/pages/chat/messages/messages.page.html b/src/app/pages/chat/messages/messages.page.html index cf14f59d9..14deccc04 100644 --- a/src/app/pages/chat/messages/messages.page.html +++ b/src/app/pages/chat/messages/messages.page.html @@ -49,7 +49,7 @@ -->
-
@@ -76,7 +76,7 @@
- + {{file.description}} {{msg.file.type.replace('application/','').toUpperCase()}} diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 42e82d4c8..f7f49ba3d 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -1,6 +1,6 @@ import { AfterViewChecked, AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router' -import { GestureController, Gesture, ModalController, NavParams, PopoverController, IonSlides } from '@ionic/angular'; +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'; import { EventPerson } from 'src/app/models/eventperson.model'; @@ -24,6 +24,8 @@ import { Filesystem, Directory, Encoding } from '@capacitor/filesystem'; import { VoiceRecorder, VoiceRecorderPlugin, RecordingData, GenericResponse, CurrentRecordingStatus } from 'capacitor-voice-recorder'; import { Haptics, ImpactStyle } from '@capacitor/haptics'; import { PreviewCameraPage } from 'src/app/modals/preview-camera/preview-camera.page'; +import { SqliteService } from 'src/app/services/sqlite.service'; +import { elementAt } from 'rxjs-compat/operator/elementAt'; const IMAGE_DIR = 'stored-images'; @@ -89,9 +91,12 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { private processes: ProcessesService, public ThemeService: ThemeService, private changeDetectorRef: ChangeDetectorRef, + private platform: Platform, + private sqlservice: SqliteService ) { this.loggedUser = authService.ValidatedUserChat['data']; this.roomId = this.navParams.get('roomId'); + console.log('ROOM ID', this.roomId) window.onresize = (event) => { if( window.innerWidth > 701){ @@ -111,6 +116,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { directory: Directory.Data, recursive: true }); + this.getRoomMessageDB(this.roomId); } ngAfterViewInit() { @@ -544,6 +550,71 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { }); } + getRoomMessageDB(roomId) { + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + } else { + this.sqlservice.getAllChatMSG(roomId).then((msg: any) => { + let chatmsgArray = []; + let array = [] + msg.forEach(element => { + 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 + } + + chatmsgArray.push(msgChat) + }); + + this.messages = chatmsgArray.reverse(); + console.log('CHAT MSG FROM DB', chatmsgArray) + }) + } + } + + isJson(str) { + try { + JSON.parse(str); + } catch (e) { + return ""; + } + return JSON.parse(str); +} + + + + transformDataMSG(res) { + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + } else { + res.forEach(element => { + 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 + } + + this.sqlservice.addChatMSG(chatmsg) + }); + } + + } + async serverLongPull() { const roomId = this.roomId @@ -557,6 +628,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { this.chatService.getRoomMessages(roomId).subscribe(async res => { console.log("Chat message",res) + this.transformDataMSG(res['messages']) + this.getRoomMessageDB(this.roomId); + if (res == 502) { // Connection timeout @@ -568,8 +642,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { // Show Error //showMessage(response.statusText); //this.loadMessages() - this.messages = res['messages'].reverse(); - this.chatMessageStore.add(roomId, this.messages) + //this.messages = res['messages'].reverse(); + //this.chatMessageStore.add(roomId, this.messages) //console.log(this.messages); // Reconnect in one second diff --git a/src/app/services/sqlite.service.ts b/src/app/services/sqlite.service.ts index 01bd2cfb6..ce10d1711 100644 --- a/src/app/services/sqlite.service.ts +++ b/src/app/services/sqlite.service.ts @@ -14,11 +14,17 @@ export class SqliteService { readonly allprocess: string = "ALLPROCESS"; readonly actions: string = "ACTIONS"; readonly publications: string = "PUBLICATIONS"; + readonly chatlistroom: string = "CHATLISTROOM"; + readonly chatlistUsers: string = "CHATLISTUSERS"; + readonly chatmsg: string = "CHATMSG"; EVENTS: Array; EXPEDIENTES: Array; ALLPROCESS: Array; PROCESS: Array; ALLACTIONS: Array; + ALLChatROOM: Array; + ALLChatUSERs: Array; + ALLCHATMSG: Array; constructor(private platform: Platform, private sqlite: SQLite) { @@ -127,8 +133,55 @@ export class SqliteService { console.log("Sucess action Table created: ", res) }) .catch((error) => console.log(JSON.stringify(error))); + + await sqLite.executeSql(` + CREATE TABLE IF NOT EXISTS ${this.chatlistroom} ( + Id varchar(255) PRIMARY KEY, + Uids Text, + Usernames Text, + LastMessage Text, + UpdatedAt varchar(255) + )`, []) + .then((res) => { + console.log("Sucess chat list room Table created: ", res) + }) + .catch((error) => console.log(JSON.stringify(error))); + + await sqLite.executeSql(` + CREATE TABLE IF NOT EXISTS ${this.chatlistUsers} ( + Id varchar(255) PRIMARY KEY, + Name varchar(255), + Username varchar(255) + + )`, []) + .then((res) => { + console.log("Sucess chat list users Table created: ", res) + }) + .catch((error) => console.log(JSON.stringify(error))); + + await sqLite.executeSql(` + CREATE TABLE IF NOT EXISTS ${this.chatmsg} ( + Id varchar(255) PRIMARY KEY, + Attachments Text, + Channels Text, + File Text, + Mentions Text, + Msg varchar(255), + Rid varchar(255), + Ts varchar(255), + U Text, + UpdatedAt varchar(255) + )`, []) + .then((res) => { + console.log("Sucess chat msg Table created: ", res) + }) + .catch((error) => console.log(JSON.stringify(error))); + + }) .catch((error) => console.log(JSON.stringify(error))); + + }).catch((error) => { console.log('Platform ready error', error) }); @@ -191,6 +244,48 @@ export class SqliteService { }); } + //chatlistroom + 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}')`, []) + .then(() => { + console.log("chat room add with Success"); + + }, (e) => { + console.log(JSON.stringify(e.err)); + }); + } + + //chatlistusers + public addChatListUsers(data) { + console.log('INSIDE DB CHAT LIST ROOM',data,) + this.dbInstance.executeSql(` + INSERT OR REPLACE INTO ${this.chatlistUsers} (Id,Name,Username) + VALUES ('${data.id}','${data.name}','${data.username}')`, []) + .then(() => { + console.log("chat users add with Success"); + + }, (e) => { + console.log(JSON.stringify(e.err)); + }); + } + + //chatlistusers + public addChatMSG(data) { + console.log('INSIDE DB CHAT MSG',data,) + this.dbInstance.executeSql(` + INSERT OR REPLACE INTO ${this.chatmsg} (Id,Attachments,Channels,File,Mentions,Msg,Rid, Ts ,U, UpdatedAt) + VALUES ('${data._id}','${JSON.stringify(data.attachments)}','${JSON.stringify(data.channels)}','${JSON.stringify(data.file)}','${JSON.stringify(data.mentions)}','${data.msg}','${data.rid}','${data.ts}','${JSON.stringify(data.u)}','${data._updatedAt}')`, []) + .then(() => { + console.log("chat msg add with Success"); + + }, (e) => { + console.log(JSON.stringify(e.err)); + }); + } + //updateevent public updateEvent(data) { this.dbInstance.executeSql(` @@ -348,6 +443,51 @@ export class SqliteService { console.log(" Get all actions error", JSON.stringify(e)); }); } + + //getAllChatRoom + getAllChatRoom() { + return this.dbInstance.executeSql(`SELECT * FROM ${this.chatlistroom}`, []).then((res) => { + this.ALLChatROOM = []; + if (res.rows.length > 0) { + for (var i = 0; i < res.rows.length; i++) { + this.ALLChatROOM.push(res.rows.item(i)); + } + return this.ALLChatROOM; + } + }, (e) => { + console.log(" Get all chat room error", JSON.stringify(e)); + }); + } + + //getAllChatUsers + getAllChatUsers() { + return this.dbInstance.executeSql(`SELECT * FROM ${this.chatlistUsers}`, []).then((res) => { + this.ALLChatUSERs = []; + if (res.rows.length > 0) { + for (var i = 0; i < res.rows.length; i++) { + this.ALLChatUSERs.push(res.rows.item(i)); + } + return this.ALLChatUSERs; + } + }, (e) => { + console.log(" Get all chat users error", JSON.stringify(e)); + }); + } + + //getAllChatMSG + getAllChatMSG(roomId) { + return this.dbInstance.executeSql(`SELECT * FROM ${this.chatmsg} WHERE Rid = ?`, [roomId]).then((res) => { + this.ALLCHATMSG = []; + if (res.rows.length > 0) { + for (var i = 0; i < res.rows.length; i++) { + this.ALLCHATMSG.push(res.rows.item(i)); + } + return this.ALLCHATMSG; + } + }, (e) => { + console.log(" Get all chat users error", JSON.stringify(e)); + }); + } //getlistOfEventAprove getListOfEventAprove(process, type) { return this.dbInstance.executeSql(`SELECT * FROM ${this.allprocess} WHERE workflowDisplayName = ? OR workflowDisplayName = ? `, [process, type]).then((res) => {