Files
doneit-web/src/app/pages/chat/chat.page.ts
T
Peter Maquiran 1a319093ee list room
2024-06-05 11:09:03 +01:00

927 lines
23 KiB
TypeScript

import { HttpHeaders, HttpParams } from '@angular/common/http';
import {
Component,
OnInit,
ViewChild,
ViewContainerRef,
Output,
NgZone,
} from '@angular/core';
import { ModalController, Platform } from '@ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { ChatService } from 'src/app/services/chat.service';
import { ChatSystemService } from 'src/app/services/chat/chat-system.service'
import { GroupMessagesPage } from './group-messages/group-messages.page';
import { ContactsPage } from './messages/contacts/contacts.page';
import { MessagesPage } from './messages/messages.page';
import { NewGroupPage } from './new-group/new-group.page';
import { EditGroupPage } from 'src/app/shared/chat/edit-group/edit-group.page';
import { Observable, Subject } from "rxjs/Rx";
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { EventPerson } from 'src/app/models/eventperson.model';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
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';
import { StorageService } from 'src/app/services/storage.service';
import { SessionStore } from 'src/app/store/session.service';
import { ChatDebuggingPage } from 'src/app/shared/popover/chat-debugging/chat-debugging.page';
import { EventTrigger } from 'src/app/services/eventTrigger.service';
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service';
import { RouteService } from 'src/app/services/route.service';
import { Plugins } from '@capacitor/core';
import { Store } from '@ngrx/store';
import { RoomRemoteDataSourceState } from 'src/app/services/Repositorys/chat/data-source/room/room-memory-data-source';
import { RoomRepositoryService } from 'src/app/services/Repositorys/chat/repository/room-repository.service'
import { RoomListOutPutDTO } from 'src/app/services/Repositorys/chat/dto/room/roomListOutputDTO';
const { App } = Plugins;
@Component({
selector: 'app-chat',
templateUrl: './chat.page.html',
styleUrls: ['./chat.page.scss'],
})
export class ChatPage implements OnInit {
showLoader: boolean;
headers: HttpHeaders;
options: any;
X_User_Id: any;
X_Auth_Token: any;
loggedUser: any;
segment: string;
allGroups: any[];
privateGroups: any[];
publicGroups: any[];
userConnectedList: any[];
userRooms: any[];
userChannels: any[];
userDirectMessages: any[];
result: any;
dmUsers: any[] = [];
idSelected: string;
desktopComponent: any = {
showMessages: false,
showGroupMessages: false,
}
@ViewChild('messagecontainer', { read: ViewContainerRef }) entry: ViewContainerRef;
componentRef: any;
roomId: any;
task: 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;
subject: any;
public messages: Subject<any>;
message = {
"msg": "connect",
"version": "1",
"support": ["1"]
};
loggedUserChat: any;
hideRefreshBtn = true;
taskParticipants: any = [];
taskParticipantsCc: any = [];
adding: "intervenient" | "CC" = "intervenient";
profile: 'mdgpr' | 'pr';
eventSelectedDate: Date = new Date();
contacts: EventPerson[];
showEventEditOrOpen: "edit" | "add" | "" | "eventoToApprove" = ""
socket: WebSocket;
receivedData: any;
routerSubscription
count$: Observable<RoomRemoteDataSourceState>;
items$!: Observable<RoomListOutPutDTO[]>;
constructor(
private chatService: ChatService,
private modalController: ModalController,
private authService: AuthService,
private route: Router,
private timeService: TimeService,
public ThemeService: ThemeService,
private dataService: DataService,
private router: Router,
private sqlservice: SqliteService,
private platform: Platform,
private storageservice: StorageService,
public ChatSystemService: ChatSystemService,
private activatedRoute: ActivatedRoute,
private eventTriger: EventTrigger,
private RochetChatConnectorService: RochetChatConnectorService,
private zone: NgZone,
public RouteService: RouteService,
private store: Store<{ chat: RoomRemoteDataSourceState }>,
private RoomRepositoryService: RoomRepositoryService
) {
this.count$ = store.select('chat');
this.headers = new HttpHeaders();
window.onresize = (event) => {
if (window.innerWidth > 701) {
this.modalController.dismiss();
}
};
this.showLoader = true;
this.segment = 'Contactos'
/* this.eventTriger.getObservable().subscribe((event) => {
if (event.notification == "recive") {
this.onSegmentChange()
}
// console.log(event)
}); */
}
// Fetch all items using useLiveQuery
ngOnInit() {
this.items$ = this.RoomRepositoryService.getItemsLive()
this.RoomRepositoryService.list();
this.segment = "Contactos";
this.authService.userData$.subscribe((res: any) => {
this.loggedUser = res;
});
this.hideRefreshButton();
this.getChatMembers();
this.router.events.forEach((event) => {
if (event instanceof NavigationEnd && event.url == '/home/chat' ||
event instanceof NavigationEnd && event.url == "/home/chat?gbCreateGroup=true") {
this.checkCreateGroup();
}
});
this.routerSubscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd && event.url.startsWith('/home/chat')) {
this.routeCheck()
}
});
}
ngOnDestroy() {
// this.setStatus('offline');
this.routerSubscription?.unsubscribe();
}
reopenWebSocketConnection() {
// Implement your reconnection logic here.
const newWebSocket = new WebSocket(environment.apiWsChatUrl);
// Add event listeners to the newWebSocket.
// Retry connecting or other reconnection logic can be added here.
}
firstEnter = true
routeCheck() {
const urlParams = new URLSearchParams(window.location.search);
const roomId = urlParams.get('roomId');
if (roomId) {
if (this.firstEnter) {
this.firstEnter = false
let delay = this.RouteService.liveHistory.find((item) => {
return ['/home/publications', '/home/agenda', '/home/gabinete', '/home/events'].filter(x => {
return item.includes(x)
}).length >= 1
})
if (!delay) {
console.log("delay")
setTimeout(() => {
this.openChat(roomId)
}, 2000)
} else {
console.log("no dalay")
this.openChat(roomId)
}
} else {
this.openChat(roomId)
}
}
}
openFailed = 0
openChat(roomId) {
const room = this.ChatSystemService.getRoomById(roomId);
if (room) {
this.openFailed = 0
if (room.isGroup) {
this.segment = 'Grupos'
this.openGroupMessagesPage(roomId)
} else {
this.segment = 'Contactos'
this.openMessagesPage(roomId)
}
} else {
if (this.openFailed <= 3) {
this.openFailed++
setTimeout(() => {
this.openChat(roomId)
}, 1000)
} else {
this.openFailed = 0
}
}
}
checkCreateGroup() {
if (this.dataService.get("newGroup")) {
this.openNewGroupPage();
}
else {
this.closeAllDesktopComponents();
this.showEmptyComponent = true;
}
}
numSequence(n: number): Array<number> {
return Array(n);
}
setStatus(status: string) {
let body = {
message: '',
status: status,
}
this.chatService.setUserStatus(body).subscribe(res => {
})
}
hideRefreshButton() {
window.onresize = (event) => {
if (window.innerWidth < 701) {
this.idSelected = '';
this.hideRefreshBtn = false;
this.closeAllDesktopComponents()
this.ChatSystemService.getRoomById(this.roomId)?.roomLeave()
}
else {
this.hideRefreshBtn = true;
if (this.idSelected == '') {
this.showEmptyComponent = true;
}
}
}
if (window.innerWidth < 701) {
this.idSelected = '';
this.hideRefreshBtn = false;
}
}
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;
}
showEmptyContainer() {
this.idSelected = '';
this.showEmptyComponent = true;
}
openGroupContactsPage(data) {
this.idSelected = '';
this.groupRoomId = data;
this.closeAllDesktopComponents();
if (window.innerWidth < 701) {
}
else {
this.showGroupContacts = true;
}
}
openMessagesPage(rid) {
console.log('rid', rid);
// this.chatService.refreshtoken();
this.roomId = rid;
if (window.innerWidth < 701) {
this.openMessagesModal(rid);
}
else {
this.idSelected = rid;
this.closeAllDesktopComponents();
this.showEmptyComponent = false;
this.showMessages = true;
}
}
openContactsPage() {
this.segment = 'Contactos';
this.idSelected = '';
this.closeAllDesktopComponents();
if (window.innerWidth < 701) {
this.selectContact();
}
else {
this.showEmptyComponent = false;
this.showContacts = true;
}
}
openNewGroupPage() {
this.segment = 'Grupos';
this.idSelected = '';
if (window.innerWidth < 701) {
this.newGroup();
}
else {
this.closeAllDesktopComponents();
this.showEmptyComponent = false;
this.showNewGroup = true;
}
}
openEditGroupPage(rid) {
if (window.innerWidth < 701) {
this.editGroup(rid);
}
else {
this.closeAllDesktopComponents();
this.showEditGroup = true;
}
}
openGroupMessagesPage(rid) {
this.roomId = rid;
if (window.innerWidth < 701) {
this.openGroupMessagesModal(rid);
}
else {
this.idSelected = rid;
this.closeAllDesktopComponents();
this.showEmptyComponent = false;
this.showGroupMessages = true;
}
}
openNewEventPage(data?) {
if (data) {
this.taskParticipants = data.members.map((val) => {
return {
Name: val.name,
EmailAddress: val.username + "@" + environment.domain,
IsRequired: "true",
}
});
this.groupRoomId = data.roomId;
}
this.closeAllDesktopComponents();
if (window.innerWidth < 701) {
}
else {
this.showNewEvent = true;
}
}
async openAttendeesComponent(data) {
this.adding = data.type
this.closeAllDesktopComponents();
this.showAttendees = true;
}
async clearContact() {
this.contacts = [];
}
async setContact(data: EventPerson[]) {
this.contacts = data;
}
async setIntervenient(data) {
this.taskParticipants = removeDuplicate(data)
}
async setIntervenientCC(data) {
this.taskParticipantsCc = removeDuplicate(data)
}
async closeAttendeesComponent() {
this.closeAllDesktopComponents();
this.showNewEvent = true;
}
async closeNewEventComponent() {
this.closeAllDesktopComponents();
this.showEmptyComponent = true;
this.idSelected = "";
}
async closeNewEventComponentAndOpenChat({ roomId }) {
this.closeAllDesktopComponents();
this.ChatSystemService._group.forEach((room) => {
if (room.id == roomId) {
this.openGroupMessagesPage(roomId)
}
})
this.ChatSystemService._dm.forEach((room) => {
if (room.id == roomId) {
this.openMessagesPage(roomId)
}
})
}
onSegmentChange() {
this.ChatSystemService.getAllRooms();
this.ChatSystemService._dm
}
doRefresh(event) {
setTimeout(() => {
try {
event?.target?.complete();
} catch (error) { }
}, 1000);
}
customRoom() {
let params = new HttpParams();
params = params.set("types", "c");
this.chatService.customsRooms(params).subscribe(res => {
//
});
}
// 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;
// });
// //
// //
// }).catch((error) => {
// console.error('storage getdirectmessagedb: ',error)
// })
// this.storageservice.get('chatusers').then((users) => {
// this.dmUsers = users.filter(data => data.username != SessionStore.user.UserName);
// }).catch((error) => {
// console.error('storage getchatusers: ',error)
// })
// }
// // else {
// // this.sqlservice.getAllChatRoom().then((rooms: any) => {
// // //
// // let roomsArray = [];
// // rooms.forEach(element => {
// // let roomListDB = {
// // _id: element.Id,
// // uids: this.isJson(element.Uids),
// // usernames: this.isJson(element.Usernames),
// // lastMessage: this.isJson(element.LastMessage),
// // _updatedAt: element.UpdatedAt
// // }
// // if(element.customFields == "undefined") {
// // roomsArray.push(roomListDB)
// // }
// // });
// // this.userDirectMessages = roomsArray.sort((a, b) => {
// // var dateA = new Date(a._updatedAt).getTime();
// // var dateB = new Date(b._updatedAt).getTime();
// // return dateB - dateA;
// // });
// // //
// // //
// // })
// // this.sqlservice.getAllChatUsers().then((userslist: any) => {
// // //
// // let chatusersArray = [];
// // userslist.forEach(element => {
// // let userListDB = {
// // _id: element.Id,
// // name: element.Name,
// // username: element.Username
// // }
// // chatusersArray.push(userListDB);
// // });
// // this.dmUsers = chatusersArray.filter(data => data.username != SessionStore.user.UserName);
// // })
// // }
// }
// 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
// }
// //
// roomsArray.push(roomList)
// });
// this.storageservice.remove('rooms');
// this.storageservice.store('rooms', roomsArray);
// } else {
// data.forEach(element => {
// let roomList = {
// id: element._id,
// uids: element.uids,
// usernames: element.usernames,
// lastMessage: element.lastMessage,
// updatedat: element._updatedAt
// }
// //
// // this.sqlservice.addChatListRoom(roomList);
// });
// }
// }
async transformDataUserList(users) {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
let usersArray = [];
users.forEach(element => {
//
let chatusers = {
_id: element._id,
name: element.name,
username: element.username
}
//
usersArray.push(chatusers);
});
await this.storageservice.remove('chatusers');
await this.storageservice.store('chatusers', usersArray);
} else {
users.forEach(element => {
//
let chatusers = {
id: element._id,
name: element.name,
username: element.username
}
//
// this.sqlservice.addChatListUsers(chatusers);
});
}
}
showDateDuration(start: any) {
return this.timeService.showDateDuration(start);
}
countDownDate(date: any, roomId: string) {
return this.timeService.countDownDate(date, roomId);
}
async getChatMembers() {
this.chatService.getAllUsers().subscribe(res => {
//
this.transformDataUserList(res['users'])
});
}
getGroupsDB() {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.storageservice.get("grouprooms").then((rooms) => {
let k = rooms.sort((a, b) => {
var dateA = new Date(a._updatedAt).getTime();
var dateB = new Date(b._updatedAt).getTime();
return dateB - dateA;
});
this.allGroups = rooms.sort((a, b) => {
var dateA = new Date(a._updatedAt).getTime();
var dateB = new Date(b._updatedAt).getTime();
return dateB - dateA;
});
//
}).catch((error) => {
console.error('storage getGrup Romm db: ', error)
})
this.storageservice.get('chatusers').then((users) => {
this.dmUsers = users.filter(data => data.username != SessionStore.user.UserName);
}).catch((error) => {
console.error('storage getgrupDb: ', error)
})
} 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;
// });
// //
// })
}
}
roomDataFileType(roomData) {
return roomData?.lastMessage?.file?.type || null
}
async 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
}
groupsArray.push(roomList)
});
await this.storageservice.remove('grouprooms');
await 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
}
// this.sqlservice.addChatListRoom(roomList);
});
}
}
async emptyTextDescriptionOpen() {
this.closeAllDesktopComponents()
this.showEmptyComponent = true
}
async getGroups(event?) {
this.result = this.chatService.getAllPrivateGroups().subscribe(async (res: any) => {
//
this.showLoader = false;
if (res.groups != 200) {
this.transformGroups(res.groups);
this.getGroupsDB();
this.privateGroups = res.groups;
if (this.route.url != "/home/chat") {
//
}
else {
//Check if modal is opened
if (this.segment == "Grupos" && this.showGroupMessages != true) {
await new Promise(resolve => setTimeout(resolve, 1000)).catch((error) => {
console.error(error);
});
//await this.getGroups();
}
}
}
else {
//await this.getGroups();
}
});
}
isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return str;
}
return JSON.parse(str);
}
async selectContact() {
const modal = await this.modalController.create({
component: ContactsPage,
cssClass: 'modal modal-desktop',
});
modal.onDidDismiss().then((Data) => {
// let data = Data.data
// let roomId = data.roomId
// this.openMessagesPage(roomId);
});
await modal.present();
}
async newGroup() {
const modal = await this.modalController.create({
component: NewGroupPage,
cssClass: 'modal modal-desktop',
});
await modal.present();
modal.onDidDismiss();
}
async editGroup(roomId) {
const modal = await this.modalController.create({
component: EditGroupPage,
cssClass: 'modal modal-desktop',
componentProps: {
roomId: roomId,
},
});
modal.onDidDismiss().then((res) => {
this.modalController.dismiss(res.data);
});
await modal.present();
}
async openMessagesModal(roomId: any) {
this.closeAllDesktopComponents();
//
const modal = await this.modalController.create({
component: MessagesPage,
cssClass: 'modal modal-desktop isMessagesChatOpened',
componentProps: {
roomId: roomId,
},
});
await modal.present();
modal.onDidDismiss();
}
backToChat({ roomId }) {
const room = this.ChatSystemService.getRoomById(roomId);
if (room.isGroup) {
this.segment = "Grupos"
this.openGroupMessagesPage(room.id);
} else {
this.segment = "Contactos"
this.openMessagesPage(room.id);
}
}
async openChatDebuggingPageModal(roomId?: any) {
const modal = await this.modalController.create({
component: ChatDebuggingPage,
cssClass: 'modal modal-desktop isMessagesChatOpened',
componentProps: {
// roomId: roomId,
},
});
modal.onDidDismiss();
await modal.present();
}
async openGroupMessagesModal(roomId: any) {
const modal = await this.modalController.create({
component: GroupMessagesPage,
cssClass: 'modal modal-desktop isGroupChatOpened',
componentProps: {
roomId: roomId,
},
});
modal.onDidDismiss().then(() => {
this.ChatSystemService.currentRoom.roomLeave()
});
await modal.present();
}
reloadComponent(self: boolean, urlToNavigateTo?: string) {
//skipLocationChange:true means dont update the url to / when navigating
console.log("Current route I am on:", this.router.url);
const url = self ? this.router.url : urlToNavigateTo;
this.zone.run(() => this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.zone.run(() => this.router.navigate([`/${url}`]).then(() => {
console.log(`After navigation I am on:${this.router.url}`)
}))
}))
}
}