Files
doneit-web/src/app/shared/chat/messages/messages.page.ts
T
tiago.kayaya 55ebb0219e save
2021-08-20 11:24:42 +01:00

323 lines
8.3 KiB
TypeScript

import { AfterViewChecked, Component, ElementRef, Input, OnChanges, OnInit, SimpleChanges, ViewChild } from '@angular/core';
import { AnimationController, ModalController, PopoverController } from '@ionic/angular';
import { AlertService } from 'src/app/services/alert.service';
import { AuthService } from 'src/app/services/auth.service';
import { ChatService } from 'src/app/services/chat.service';
import { ToastService } from 'src/app/services/toast.service';
import { ChatOptionsPopoverPage } from 'src/app/shared/popover/chat-options-popover/chat-options-popover.page';
import { MessagesOptionsPage } from 'src/app/shared/popover/messages-options/messages-options.page';
import { ContactsPage } from '../new-group/contacts/contacts.page';
import { Router } from '@angular/router';
import { connection } from 'src/app/services/socket/synchro.service';
import { ChatOptionsFeaturesPage } from 'src/app/modals/chat-options-features/chat-options-features.page';
@Component({
selector: 'app-messages',
templateUrl: './messages.page.html',
styleUrls: ['./messages.page.scss'],
})
export class MessagesPage implements OnInit, AfterViewChecked, OnChanges {
showLoader: boolean;
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
loggedUser: any;
message = '';
messages:any;
dm:any;
userPresence='';
dmUsers:any;
checktimeOut: boolean;
@Input() roomId:string;
@Input() showMessages:string;
connection = connection
constructor(
public popoverController: PopoverController,
private modalController: ModalController,
/* private navParams: NavParams, */
private chatService: ChatService,
private authService: AuthService,
private animationController: AnimationController,
private alertService: AlertService,
private toastService: ToastService,
private route: Router
) {
this.loggedUser = authService.ValidatedUserChat['data'];
/* this.dm = this.navParams.get('dm'); */
}
ngOnChanges(changes: SimpleChanges): void {
this.load();
//throw new Error('Method not implemented.');
}
ngOnInit() {
this.scrollToBottom();
/* setInterval(()=>{ */
this.load();
/* }, 9000); */
console.log(this.roomId);
console.log("Chat route", this.route.url)
}
ngOnDestroy(){
this.checktimeOut = false;
console.log('On Destroy')
}
notImplemented(){
this.alertService.presentAlert('Funcionalidade em desenvolvimento');
}
load = ()=>{
this.checktimeOut = true;
this.serverLongPull();
this.getChatMembers();
}
doRefresh(ev:any){
this.load();
ev.target.complete();
}
ngAfterViewChecked() {
//this.scrollToBottom();
}
scrollToBottom(): void {
try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch(err) { }
finally {
}
}
sendMessage() {
this.connection.$send({})
let body = {
"message":
{
"rid": this.roomId, "msg": this.message
}
}
this.chatService.sendMessage(body).subscribe(res=> {
});
this.message = "";
}
loadMessages(){
//this.showLoader = true;
this.chatService.getRoomMessages(this.roomId).subscribe(res => {
console.log(res);
this.messages = res['messages'].reverse();
console.log(this.messages);
//this.serverLongPull(res)
/* this.chatService.subscribe(this.roomId).then(res => {
console.log("Real fake msg", res)
}); */
//this.showLoader = false;
})
}
getChatMembers(){
console.log(this.roomId);
//this.showLoader = true;
this.chatService.getMembers(this.roomId).subscribe(res=> {
this.dmUsers = res['members'].filter(data => data.username != this.loggedUser.me.username)
console.log(res);
console.log(this.dmUsers);
this.showLoader = false;
});
}
async openMessagesOptions(ev: any) {
const popover = await this.popoverController.create({
component: MessagesOptionsPage,
componentProps: {
roomId: this.dm._id,
},
cssClass: 'messages-options',
event: ev,
translucent: true,
});
return await popover.present();
}
async addContacts(){
const modal = await this.modalController.create({
component: ContactsPage,
componentProps: {},
cssClass: 'contacts',
backdropDismiss: false
});
await modal.present();
modal.onDidDismiss();
}
openSendMessageOptions(ev?:any){
if(window.innerWidth < 701){
console.log('mobile');
this.openChatOptions(ev);
}
else{
console.log('desktop');
this._openChatOptions();
}
}
async openChatOptions(ev: any) {
const popover = await this.popoverController.create({
component: ChatOptionsPopoverPage,
cssClass: 'chat-options-popover',
event: ev,
translucent: true
});
return await popover.present();
}
async _openMessagesOptions() {
const enterAnimation = (baseEl: any) => {
const backdropAnimation = this.animationController.create()
.addElement(baseEl.querySelector('ion-backdrop')!)
.fromTo('opacity', '0.01', 'var(--backdrop-opacity)');
const wrapperAnimation = this.animationController.create()
.addElement(baseEl.querySelector('.modal-wrapper')!)
.keyframes([
{ offset: 0, opacity: '1', right: '-100%' },
{ offset: 1, opacity: '1', right: '0px' }
]);
return this.animationController.create()
.addElement(baseEl)
.easing('ease-out')
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
}
const leaveAnimation = (baseEl: any) => {
return enterAnimation(baseEl).direction('reverse');
}
/* const popover = await this.popoverController.create({
component: MessagesOptionsPage,
componentProps: {
roomId: this.dm._id,
},
cssClass: 'messages-options',
event: ev,
translucent: true,
});
return await popover.present(); */
const modal = await this.modalController.create({
enterAnimation,
leaveAnimation,
component: MessagesOptionsPage,
cssClass: 'model profile-modal search-submodal',
componentProps: {
roomId: this.roomId,
}
});
return await modal.present();
}
async _openChatOptions() {
const enterAnimation = (baseEl: any) => {
const backdropAnimation = this.animationController.create()
.addElement(baseEl.querySelector('ion-backdrop')!)
.fromTo('opacity', '0.01', 'var(--backdrop-opacity)');
const wrapperAnimation = this.animationController.create()
.addElement(baseEl.querySelector('.modal-wrapper')!)
.keyframes([
{ offset: 0, opacity: '1', right: '-100%' },
{ offset: 1, opacity: '1', right: '0px' }
]);
return this.animationController.create()
.addElement(baseEl)
.easing('ease-out')
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
}
const leaveAnimation = (baseEl: any) => {
return enterAnimation(baseEl).direction('reverse');
}
const modal = await this.modalController.create({
enterAnimation,
leaveAnimation,
component: ChatOptionsFeaturesPage,
cssClass: 'model profile-modal search-submodal',
componentProps: {
roomId: this.roomId,
}
});
return await modal.present();
}
async serverLongPull(){
this.chatService.getRoomMessages(this.roomId).subscribe(async res => {
if (res == 502) {
// Connection timeout
// happens when the connection 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();
console.log(this.messages);
// Reconnect in one second
if(this.route.url != "/home/chat"){
console.log("Timer message stop")
} else {
if(document.querySelector('app-messages')){
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();
}
});
}
}