Files
doneit-web/src/app/ui/chat/modal/messages/messages.page.ts
T
Peter Maquiran 9fee233d91 set last message
2024-09-10 16:01:51 +01:00

1491 lines
43 KiB
TypeScript

import { AfterViewInit, Component, ElementRef, HostListener, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { GestureController, ModalController, NavParams, PopoverController, Platform } from '@ionic/angular';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { ExpedientTaskModalPageNavParamsTask } from 'src/app/models/ExpedientTaskModalPage';
import { ContactsPage } from 'src/app/ui/chat/modal/messages/contacts/contacts.page';
import { AlertService } from 'src/app/services/alert.service';
import { FileService } from 'src/app/services/functions/file.service';
import { ToastService } from 'src/app/services/toast.service';
import { ThemeService } from 'src/app/services/theme.service'
import { VoiceRecorder, GenericResponse } from 'capacitor-voice-recorder';
import { Haptics, ImpactStyle } from '@capacitor/haptics';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { SearchPage } from 'src/app/pages/search/search.page';
import { Storage } from '@ionic/storage';
import { CameraResultType } from '@capacitor/camera';
import { DomSanitizer } from '@angular/platform-browser';
import { SessionStore } from 'src/app/store/session.service';
import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page';
//======
import { Observable as DexieObservable } from 'Dexie';
import { Observable, Subscription } from 'rxjs';
import { MessageTable } from 'src/app/infra/database/dexie/instance/chat/schema/message';
import { ChatServiceService } from 'src/app/module/chat/domain/chat-service.service';
import { EditMessagePage } from 'src/app/ui/chat/modal/edit-message/edit-message.page';
import { IMessageType, MessageAttachmentFileType, MessageAttachmentSource, MessageEntity } from 'src/app/core/chat/entity/message';
import { MemberTable } from 'src/app/infra/database/dexie/instance/chat/schema/members';
import { TypingTable } from 'src/app/infra/database/dexie/instance/chat/schema/typing';
import { compressImageBase64 } from 'src/app/utils/imageCompressore';
import { FilePickerService } from 'src/app/infra/file-picker/file-picker.service'
import { RecordingData } from 'capacitor-voice-recorder';
import { Logger } from 'src/app/services/logger/main/service';
import { MessagesOptionsPage } from '../messages-options/messages-options.page';
import { ChatOptionsPopoverPage } from '../chat-options-popover/chat-options-popover.page';
import { CameraService } from 'src/app/infra/camera/camera.service'
import { FilePickerMobileService } from 'src/app/infra/file-picker/mobile/file-picker-mobile.service'
import { FilePickerWebService } from 'src/app/infra/file-picker/web/file-picker-web.service'
import { allowedDocExtension } from 'src/app/utils/allowedDocExtension';
import { JSFileToDataUrl } from 'src/app/utils/ToBase64';
import { RoomLocalRepository } from 'src/app/module/chat/data/repository/room/room-local-repository.service'
import { MemberListLocalRepository } from 'src/app/module/chat/data/repository/member/member-list-local-repository.service'
import { UserTypingLocalRepository } from 'src/app/module/chat/data/repository/typing/user-typing-local-data-source.service';
import { UserTypingRemoteRepositoryService } from 'src/app/module/chat/data/repository/typing/user-typing-live-data-source.service';
import { MessageLocalDataSourceService } from 'src/app/module/chat/data/repository/message/message-local-data-source.service';
import { RoomType } from "src/app/core/chat/entity/group";
import { RoomTable } from 'src/app/infra/database/dexie/instance/chat/schema/room';
import { whatsappDate } from 'src/app/ui/shared/utils/whatappdate';
import { MessageViewModal } from '../../store/model/message';
import { XBallon } from '../../utils/messageBallon';
import { tap } from 'rxjs/operators';
import { ChatPopoverPage } from '../chat-popover/chat-popover.page';
import { ViewOncesImagePageInput, ViewOncesImagePage } from '../view-onces/view-onces.page';
import { LastMessage } from '../../utils/lastMessage';
const IMAGE_DIR = 'stored-images';
@Component({
selector: 'app-messages',
templateUrl: './messages.page.html',
styleUrls: ['./messages.page.scss'],
})
export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
showLoader: boolean;
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
@ViewChild('rectangle') private rectangle: ElementRef;
canvas: any
ctx: any
loggedUser: any;
userPresence = '';
dmUsers: any;
roomId: string;
el: any;
members: any;
scrollingOnce: boolean = true;
private scrollChangeCallback: () => void;
currentPosition: any;
startPosition: number;
scrollToBottomBtn = false;
showMessageOptions = false;
selectedMsgId: string;
dicIndex = 0;
task: ExpedientTaskModalPageNavParamsTask;
LoadedDocument: any = null;
recording = false;
allowTyping = true;
storedFileNames = [];
lastAudioRecorded = '';
audioRecorded: any = "";
audioDownloaded: any = "";
durationDisplay = '';
duration = 0;
@ViewChild('recordbtn', { read: ElementRef }) recordBtn: ElementRef;
myAudio: any;
downloadfile: any;
downloadFile: any;
files: any[] = [];
@ViewChild('filechooser') fileChooserElementRef: ElementRef;
@ViewChild('array') myInputRef!: ElementRef;
//items: File[] = [];
fileSelected?: Blob;
pdfUrl?: string;
base64File: string;
downloadProgess: number;
downloadLoader: boolean;
audioPermissionStatus: 'granted' | 'denied' | 'prompt' | null = null
sessionStore = SessionStore
SessionStore = SessionStore
roomData$: Observable<RoomTable | undefined>
roomStatus$: DexieObservable<Boolean >
roomMessage$: DexieObservable<MessageTable[]>
roomMembers$: Observable<MemberTable[]>
//userTyping$: DexieObservable<TypingTable[] | undefined>
userTyping$: TypingTable[] | undefined
newMessagesStream!: Subscription
selectedMessage: any = null;
emojis: string[] = ['😊', '😂', '❤️', '👍', '😢']; // Add more emojis as needed
textField = ''
roomType!: RoomType
messageReceiveSubject: Subscription
messageDeleteSubject: Subscription
messageUpdateSubject: Subscription
messageSendSubject: Subscription
messages1: {[key: string]: MessageViewModal[]} = {}
MessageAttachmentFileType = MessageAttachmentFileType
MessageAttachmentFileSource = MessageAttachmentSource
messageOnReconnectSubject: Subscription
date: {[key: string]: Object} = {}
totalMembers = 0
isAdmin = true
RoomTypeEnum = RoomType
IMessageType = IMessageType
handleClickActive = true
constructor(
public popoverController: PopoverController,
private modalController: ModalController,
private navParams: NavParams,
private alertService: AlertService,
private toastService: ToastService,
private fileService: FileService,
private gestureController: GestureController,
public ThemeService: ThemeService,
private platform: Platform,
private storage: Storage,
private sanitiser: DomSanitizer,
private chatServiceService: ChatServiceService,
private FilePickerService: FilePickerService,
private CameraService: CameraService,
private FilePickerMobileService: FilePickerMobileService,
private FilePickerWebService: FilePickerWebService,
private RoomLocalRepository: RoomLocalRepository,
private MemberListLocalRepository: MemberListLocalRepository,
private userTypingLocalRepository: UserTypingLocalRepository,
private UserTypingRemoteRepositoryService: UserTypingRemoteRepositoryService,
private messageLocalDataSourceService: MessageLocalDataSourceService,
) {
this.roomId = this.navParams.get('roomId');
this.roomData$ = this.RoomLocalRepository.getRoomByIdLive(this.roomId)
this.roomData$.subscribe(e => {
// console.log(e)
if(e) {
this.roomType = e.roomType
}
})
this.getMessages();
this.listenToIncomingMessage();
this.listenToDeleteMessage();
this.listenToUpdateMessage();
this.listenToSendMessage();
// this.roomMessage$ = this.messageRepositoryService.getItemsLive(this.roomId)
this.roomMembers$ = this.MemberListLocalRepository.getRoomMemberByIdLive(this.roomId).pipe(
tap((members) => {
this.totalMembers = members.length
this.members = members
for(const member of members) {
if(member.wxUserId == SessionStore.user.UserId) {
this.isAdmin = member.isAdmin
}
}
})
)
this.roomStatus$ = this.MemberListLocalRepository.allMemberOnline(this.roomId)
// this.roomRepositoryService.getRoomById(this.roomId)
this.userTypingLocalRepository.getUserTypingLive().subscribe((e) => {
const arrayNames = e.map(e => e.userName)
this.userTyping$ = e as any
const uniqueArray = [...new Set(arrayNames)];
(this.myInputRef.nativeElement as HTMLDivElement).innerHTML = '::'+ uniqueArray
})
this.chatServiceService.removeBoldFromRoom({roomId: this.roomId})
this.chatServiceService.getRoomById(this.roomId)
}
@HostListener('document:click', ['$event'])
handleClickOutside(event: Event) {
if (!this.handleClickActive) return;
const clickedInside = (event.target as HTMLElement).closest('.mat-menu-content');
if (!clickedInside) {
this.selectedMessage = null;
}
}
async getMessages() {
// dont remove this line
this.messages1[this.roomId] = []
let messages = await this.messageLocalDataSourceService.getItems(this.roomId)
this.messages1[this.roomId] = []
this.date = {}
const allMessage = [];
// let ids = {}
// messages = messages.filter((message: any) => {
// if (message.$createAt) {
// if (!ids[message.$createAt]) {
// ids[message.$createAt] = true;
// return true; // Keep this message
// } else {
// console.log('delete');
// return false; // Remove this message
// }
// }
// return true; // Keep messages without an id
// });
console.time("mappingTime");
for(const message of messages) {
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(message)
allMessage.push(Ballon)
}
allMessage.push(new MessageViewModal(message))
}
console.timeEnd("mappingTime");
this.messages1[this.roomId] = allMessage
this.loadAttachment()
setTimeout(() => {
this.sendReadMessage()
}, 1000)
this.messageOnReconnectSubject?.unsubscribe()
this.messageOnReconnectSubject = this.chatServiceService.listenToMessageLoadHistory({roomId: this.roomId}).subscribe((messages) => {
for(const message of messages.data) {
const found = this.messages1[this.roomId].find((e) => e.id == message.id)
if(!found) {
const msg = new MessageViewModal(message as any)
Object.assign(msg, message)
this.messages1[this.roomId].push(msg)
}
}
})
}
sendReadMessage() {
for(const message of this.messages1[this.roomId]) {
if(!message.meSender()) {
const me = message.haveSeen(message.info)
if(!me) {
Logger.info('send read at, sender '+ message.sender.wxFullName+ ' '+ message.message +'message id'+ message.id)
this.chatServiceService.sendReadAt({
memberId: SessionStore.user.UserId,
messageId: message.id,
requestId: '',
roomId: this.roomId
})
}
}
}
}
async loadAttachment() {
for(const message of this.messages1[this.roomId]) {
if(message.hasAttachment && message.attachments[0].source != MessageAttachmentSource.Webtrix) {
this.chatServiceService.getMessageAttachmentByMessageId(message).then((result)=> {
if(result.isOk()) {
message.attachments[0].safeFile = result.value
if(result.value.startsWith('blob:http')) {
message.attachments[0].blobURl = true
}
}
})
}
}
}
messageStatus(message: MessageViewModal) {
if(this.allViewed(message)) {
return 'allViewed'
} else if(this.allReceived(message)) {
return 'allReceived'
} else if (message.messageStatus == 'send') {
return 'enviado'
} else {
return 'enviar'
}
}
allReceived(message: MessageViewModal) {
return message.info.filter(e => typeof e.deliverAt == 'string').length == this.totalMembers
}
allViewed(message: MessageViewModal) {
const totalMembers = this.members.filter((e) => message.sender.wxUserId != e.wxUserId ).length
return message.info.filter(e => typeof e.readAt == 'string' && message.sender.wxUserId != e.memberId ).length == totalMembers
}
ngOnInit() {}
ngAfterViewInit() {
this.scrollChangeCallback = () => this.onContentScrolled(event);
window.addEventListener('scroll', this.scrollChangeCallback, true);
const longpress = this.gestureController.create({
el: this.recordBtn.nativeElement,
threshold: 0,
gestureName: 'long-press',
onStart: ev => {
Haptics.impact({ style: ImpactStyle.Light })
this.startRecording();
//this.calculateDuration();
},
onEnd: ev => {
Haptics.impact({ style: ImpactStyle.Light })
this.stopRecording();
}
}, true);
longpress.enable();
}
onDragOver(e?) { }
onDragLeave(e?) { }
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');
this.durationDisplay = `${minutes}:${seconds}`;
setTimeout(() => {
this.calculateDuration();
}, 1000)
}
listenToIncomingMessage() {
this.messageReceiveSubject?.unsubscribe();
this.messageReceiveSubject = this.chatServiceService.listenToIncomingMessage(this.roomId).subscribe(async (_message) => {
const date = whatsappDate(_message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(_message)
this.messages1[this.roomId].push(Ballon)
}
const message = new MessageViewModal(_message)
this.messages1[this.roomId].push(new MessageViewModal(message))
if(message.hasAttachment) {
const result = await this.chatServiceService.downloadMessageAttachmentByMessageId({
$messageId: message.id,
id: message.attachments[0].id
})
if(result.isOk()) {
message.attachments[0].safeFile = result.value
if((result.value as unknown as string).startsWith('blob:http')) {
message.attachments[0].blobURl = true
} else {
message.attachments[0].blobURl = false
}
}
}
setTimeout(() => {
this.scrollToBottomClicked()
}, 100)
setTimeout(() => {
this.chatServiceService.removeBoldFromRoom({roomId: this.roomId})
}, 1000)
});
}
listenToDeleteMessage() {
this.messageDeleteSubject?.unsubscribe();
this.messageDeleteSubject = this.chatServiceService.listenToDeleteMessage(this.roomId).subscribe((deleteMessage) => {
console.log('delete class', deleteMessage);
const index = this.messages1[this.roomId].findIndex(e => e?.id === deleteMessage.id); // Use triple equals for comparison
this.messages1[this.roomId][index].delete()
// if (index !== -1) { // Check if the item was found
// console.log('delete ==')
// this.messages1[this.roomId].splice(index, 1);
// // console.log('removed index', index);
// } else {
// // console.log('message not found');
// }
});
}
listenToUpdateMessage() {
this.messageUpdateSubject?.unsubscribe();
this.messageUpdateSubject = this.chatServiceService.listenToUpdateMessage(this.roomId).subscribe((updateMessage) => {
const index = this.messages1[this.roomId].findIndex(e => e?.id === updateMessage.id); // Use triple equals for comparison
if (index !== -1) { // Check if the item was found
this.messages1[this.roomId][index].message = updateMessage.message
this.messages1[this.roomId][index].reactions = updateMessage.reactions
this.messages1[this.roomId][index].reactions = updateMessage.reactions
} else {
// console.log('message not found');
}
});
}
listenToSendMessage() {
this.messageSendSubject?.unsubscribe();
this.messageSendSubject = this.chatServiceService.listenToSendMessage(this.roomId).subscribe((updateMessage) => {
const index = this.messages1[this.roomId].findIndex(e => e?.requestId === updateMessage.requestId); // Use triple equals for comparison
if (index !== -1) { // Check if the item was found
this.messages1[this.roomId][index].id = updateMessage.id
this.messages1[this.roomId][index].info = updateMessage.info
let attachmentIndex = 0;
for(const attachment of updateMessage.attachments) {
this.messages1[this.roomId][index].attachments[attachmentIndex].id = attachment.id
attachmentIndex++;
}
} else {
// console.log('message not found');
}
});
}
async loadFiles() {
this.storage.get('fileName').then((fileName) => {
this.lastAudioRecorded = fileName;
})
try {
this.storage.get('recordData').then((recordData) => {
if (recordData?.value?.recordDataBase64.includes('data:audio')) {
this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(recordData?.value?.recordDataBase64);
}
else if (recordData?.value?.mimeType && recordData?.value?.recordDataBase64) {
this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(`data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`);
}
});
} catch (error) { }
}
async startRecording() {
VoiceRecorder.requestAudioRecordingPermission();
if (await VoiceRecorder.canDeviceVoiceRecord().then((result: GenericResponse) => { return result.value })) {
if (await VoiceRecorder.requestAudioRecordingPermission().then((result: GenericResponse) => { return result.value })) {
//if(await this.hasAudioRecordingPermission()){
if (this.recording) {
return;
}
this.recording = true;
VoiceRecorder.startRecording();
this.calculateDuration();
//}
}
else {
this.toastService._badRequest('Para gravar uma mensagem de voz, permita o acesso do Gabinete Digital ao seu microfone.');
}
}
else {
this.toastService._badRequest('Este dispositivo não tem capacidade para gravação de áudio!');
}
}
stopRecording() {
this.deleteRecording();
this.allowTyping = false;
if (!this.recording) {
return;
}
this.recording = false;
VoiceRecorder.stopRecording().then(async (result: RecordingData) => {
this.recording = false;
if (result.value && result.value.recordDataBase64) {
const recordData = result.value.recordDataBase64;
//
const fileName = new Date().getTime() + ".mp3";
//Save file
this.storage.set('fileName', fileName);
this.storage.set('recordData', result).then(() => {
})
}
})
setTimeout(async () => {
this.loadFiles();
}, 1000);
}
async deleteRecording() {
this.storage.remove('fileName');
this.storage.remove('recordData');
this.allowTyping = true;
this.lastAudioRecorded = '';
this.loadFiles();
}
handlePress(id?: string) {
this.selectedMsgId = id;
this.showMessageOptions = true;
}
handleClick() {
this.showMessageOptions = false;
this.selectedMsgId = "";
}
deleteMessage(msgId: string) {}
notImplemented() {
this.alertService.presentAlert('Funcionalidade em desenvolvimento');
}
close() {
this.modalController.dismiss();
this.deleteRecording();
}
load() {
this.getChatMembers();
}
doRefresh(ev: any) {
this.load();
ev.target.complete();
}
scrollToBottom(): void {
try {
if (this.scrollingOnce) {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
//this.scrollingOnce = false;
}
} catch (err) { }
}
scrollToBottomClicked = () => {
try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch (err) { }
}
async goToEvent(event: any) {
let classs;
if (window.innerWidth < 701) {
classs = 'modal modal-desktop'
} else {
classs = 'modal modal-desktop showAsideOptions'
}
const modal = await this.modalController.create({
component: ViewEventPage,
componentProps: {
eventId: event.id,
CalendarId: event.calendarId
},
cssClass: classs,
});
await modal.present();
modal.onDidDismiss().then((res) => {
});
}
onContentScrolled(e) {
this.startPosition = e.srcElement.scrollTop;
let scroll = e.srcElement.scrollTop;
let windowHeight = e.srcElement.scrollHeight;
let containerHeight = windowHeight - e.srcElement.clientHeight;
if (scroll > this.currentPosition) {
} else {
this.scrollingOnce = false;
}
if ((containerHeight - 100) > scroll) {
this.scrollToBottomBtn = true;
}
else {
this.scrollToBottomBtn = false;
}
this.currentPosition = scroll;
}
ngOnDestroy() {
window.removeEventListener('scroll', this.scrollChangeCallback, true);
this.handleClickActive = false; // Disable the listener before component destruction
}
async sendMessage() {
const message = new MessageViewModal();
message.message = this.textField
message.roomId = this.roomId
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.sentAt = new Date().toISOString()
this.textField = ''
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(message)
this.messages1[this.roomId].push(Ballon)
}
this.messages1[this.roomId].push(message)
setTimeout(() => {
this.scrollToBottomClicked()
}, 100)
const data = await this.chatServiceService.sendMessage(message, this.roomType)
}
async sendAudio(fileName) {
const roomId = this.roomId
let audioFile;
this.storage.get('recordData').then(async (recordData:RecordingData) => {
audioFile = recordData;
if (recordData?.value?.recordDataBase64.includes('data:audio')) {
this.audioRecorded = recordData?.value?.recordDataBase64;
}
else if (recordData?.value?.mimeType && recordData?.value?.recordDataBase64) {
this.audioRecorded = `data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`;
}
const audioMimeType: string = recordData.value.mimeType
const encodedData = btoa(this.audioRecorded);
const message = new MessageViewModal();
message.roomId = this.roomId
message.sentAt = new Date().toISOString()
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.attachments = [{
file: this.audioRecorded.split(',')[1],
fileName: "audio",
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Audio,
mimeType: audioMimeType, // 'audio/webm',
safeFile: this.sanitiser.bypassSecurityTrustResourceUrl(this.audioRecorded)
}]
message.sentAt = new Date().toISOString()
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(message)
this.messages1[this.roomId].push(Ballon)
}
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message, this.roomType)
setTimeout(() => {
this.scrollToBottomClicked()
}, 100)
this.deleteRecording();
});
this.deleteRecording();
}
viewDocument(file: any, url?: string) {
if (file.type == "application/webtrix") {
this.openViewDocumentModal(file);
}
else {
let fullUrl = "https://www.tabularium.pt" + url;
this.fileService.viewDocumentByUrl(fullUrl);
}
}
docIndex(index: number) {
this.dicIndex = index
}
async openViewDocumentModal(file: any) {
let task = {
serialNumber: '',
taskStartDate: '',
isEvent: true,
workflowInstanceDataFields: {
FolderID: '',
Subject: file.Assunto,
SourceSecFsID: file.ApplicationId,
SourceType: 'PDF',
SourceID: file.DocId,
DispatchNumber: ''
}
}
let doc = {
"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({
component: ViewDocumentPage,
componentProps: {
trustedUrl: '',
file: {
title: file.Assunto,
url: '',
title_link: '',
},
Document: doc,
applicationId: file.ApplicationId,
docId: file.DocId,
folderId: '',
task: task
},
cssClass: 'modal modal-desktop'
});
await modal.present();
}
getChatMembers() {}
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 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()) {
let time = start.getHours() + ":" + this.addZero(start.getUTCMinutes());
return time;
}
else {
return 'Ontem';
}
}
else {
let date = start.getDate() + "/" + (start.getMonth() + 1) + "/" + start.getFullYear();
return date;
}
}
addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
async openMessagesOptions(ev?: any) {
const popover = await this.popoverController.create({
component: ChatPopoverPage,
componentProps: {
roomId: this.roomId,
members: [],
isAdmin: this.isAdmin,
roomType: this.roomType
},
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
});
modal.onDidDismiss();
await modal.present();
}
async onImageError() {}
async onImageLoad(message: MessageViewModal, index:number) {
if(message.attachments[0].fileName == LastMessage.attachments[0].fileName) {
this.scrollToBottom()
setTimeout(() => {
this.scrollToBottom();
}, 100)
this.messages1[this.roomId].splice(index, 1);
}
}
async takePictureMobile() {
const picture = await this.CameraService.takePicture({
cameraResultType: CameraResultType.DataUrl,
quality: 90
})
if(picture.isOk()) {
const file = picture.value
const compressedImage = await compressImageBase64(
file.dataUrl,
800, // maxWidth
800, // maxHeight
0.9 // quality
)
if(compressedImage.isOk()) {
const message = new MessageViewModal();
message.roomId = this.roomId
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.attachments = [{
file: compressedImage.value.split(',')[1],
fileName: "foto",
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Image,
mimeType: 'image/'+picture.value.format
}]
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(message)
this.messages1[this.roomId].push(Ballon)
}
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message, this.roomType)
}
}
}
async addFile() {
this.addFileToChat(['.doc', '.docx', '.pdf'])
}
async addFileWebtrix() {
const modal = await this.modalController.create({
component: SearchPage,
cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop',
componentProps: {
type: 'AccoesPresidenciais & ArquivoDespachoElect',
select: true,
showSearchInput: true,
}
});
await modal.present();
modal.onDidDismiss().then(async res => {
const data = res.data;
const roomId = this.roomId
if (data.selected) {
const message = new MessageViewModal();
message.message = this.textField
message.roomId = this.roomId
message.sentAt = new Date().toISOString()
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.attachments = [{
fileName: res.data.selected.Assunto,
source: MessageAttachmentSource.Webtrix,
fileType: MessageAttachmentFileType.Doc,
applicationId: res.data.selected.ApplicationType,
docId: res.data.selected.Id,
description: res.data.selected.Assunto
}]
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(message)
this.messages1[this.roomId].push(Ballon)
}
this.messages1[this.roomId].push(message)
setTimeout(() => {
this.scrollToBottomClicked()
}, 100)
this.chatServiceService.sendMessage(message, this.roomType)
this.textField = ''
}
});
}
async pickPicture() {
const file = await this.FilePickerService.getPicture({
cameraResultType: CameraResultType.Base64
})
if(file.isOk()) {
var base64 = 'data:image/jpeg;base64,' + file.value.base64String
if (file.value.format == "jpeg" || file.value.format == "png" || file.value.format == "gif") {
const compressedImage = await compressImageBase64(
base64,
800, // maxWidth
800, // maxHeight
0.9 // quality
)
if(compressedImage.isOk()) {
const message = new MessageViewModal();
message.roomId = this.roomId
message.sentAt = new Date().toISOString()
// message.oneShot = oneShot
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.attachments = [{
file: compressedImage.value,
fileName: "foto",
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Image,
mimeType: 'image/'+file.value.format
}]
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(message)
this.messages1[this.roomId].push(Ballon)
}
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message, this.roomType)
}
}
} else {
if(file.error.type == 'PERMISSION_DENIED') {
this.toastService._badRequest("Sem acesso a camera")
}
Logger.error('failed to pick picture from the device', {
error: file.error
})
}
}
async viewOnce(event: Event, message: MessageViewModal, index:number) {
const params: ViewOncesImagePageInput = {
imageDataUrl: message.attachments[index].safeFile as any,
}
const modal = await this.modalController.create({
component: ViewOncesImagePage,
cssClass: '',
componentProps: params
});
modal.present()
return modal.onDidDismiss().then((res) => {
this.messageDelete(message)
});
}
async addFileToChat(types) {
console.log('add file ')
const roomId = this.roomId
if (this.platform.is('ios')) {
console.log('ios add file ')
const result = await this.FilePickerMobileService.getFile({
types: ['application/pdf', 'application/doc', 'application/docx','application/xls', 'application/xlsx', 'application/ppt',
'application/pptx', 'application/txt'],
multiple: false,
readData: true,
})
if(result.isOk()) {
console.log('RESULT', result.value.files[0].data)
const message = new MessageViewModal();
message.roomId = this.roomId
message.sentAt = new Date().toISOString()
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.attachments = [{
file: result.value.files[0].data,
fileName: result.value.files[0].name,
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Doc,
description: result.value.files[0].name
}]
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message, this.roomType)
return
}
}
const file = await this.FilePickerWebService.getFileFromDevice(types)
if(file.isOk()) {
console.log(file)
const fileName = file.value.name
const validation = await allowedDocExtension(fileName)
if (validation.isOk()) {
let fileBase64 = await JSFileToDataUrl(file.value);
if(fileBase64.isOk()) {
const message = new MessageViewModal();
message.roomId = this.roomId
message.sentAt = new Date().toISOString()
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.attachments = [{
file: fileBase64.value.split(',')[1],
fileName: file.value.name,
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Doc,
mimeType: file.value.type
}]
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(message)
this.messages1[this.roomId].push(Ballon)
}
this.messages1[this.roomId].push(message)
setTimeout(() => {
this.scrollToBottomClicked()
}, 100)
this.chatServiceService.sendMessage(message, this.roomType)
}
} else {
this.toastService._badRequest("Ficheiro inválido")
}
}
}
async openChatOptions(ev?: any) {
const roomId = this.roomId
const popover = await this.popoverController.create({
component: ChatOptionsPopoverPage,
cssClass: 'chat-options-popover',
event: ev,
componentProps: {
room: this.roomId,
members: this.members,
eventSelectedDate: new Date(),
},
translucent: true
});
await popover.present();
popover.onDidDismiss().then(async (res) => {
if (res['data'] == 'take-picture') {
this.takePictureMobile()
}
else if (res['data'] == 'add-picture') {
console.log('add-picture')
this.pickPicture()
}
else if (res['data'] == 'add-document') {
this.addFile()
}
else if (res['data'] == 'documentoGestaoDocumental') {
this.addFileWebtrix()
}
});
}
isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return "";
}
return JSON.parse(str);
}
async openFile(pdfString, filename, type) {
console.log('url while open ',pdfString)
/* const modal = await this.modalController.create({
component: ViewDocumentSecondOptionsPage,
componentProps: {
fileUrl: pdfString,
filename: filename
},
cssClass: 'modal modal-desktop'
});
await modal.present();
/*
await modal.present(); */
// var blob = new Blob([pdfString], { type: 'application/pdf' });
// console.log('blob blob', blob)
// this.blobToBase64(blob).then((value) => {
// console.log(value)
// }).catch((error) => {
// console.log(error)
// })
// let pathFile = ''
// const fileName = filename
// if (this.platform.is('ios')) {
// pathFile = this.file.documentsDirectory
// } else {
// pathFile = this.file.externalRootDirectory
// }
// console.log('file data', pdfString)
// console.log(pathFile)
// let removePre = this.removeTextBeforeSlash(pdfString,',')
// console.log('file data remove ', removePre)
// await Filesystem.writeFile({
// path: fileName,
// data: removePre,
// directory: Directory.Cache,
// }).then((dir) => {
// console.log('DIR ', dir)
// this.fileOpener
// .open(dir.uri, type)
// .then(() => console.log())
// .catch(e => console.error(e))
// }).catch((error) => {
// console.log('error writing the file', error)
// });
}
removeTextBeforeSlash(inputString, controlString) {
if (inputString.includes(controlString)) {
const parts = inputString.split(controlString);
return parts.length > 1 ? parts[1] : inputString;
} else {
return inputString;
}
}
downloadFileFromBrowser(fileName: string, data: any): void {
const linkSource = data;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
async openPreview(msg) {
if (msg.file.type === "application/webtrix") {
this.viewDocument(msg.file, msg.attachments.image_url)
} else {
if (!msg.attachments[0].image_url || msg.attachments[0].image_url === null || msg.attachments[0].image_url === '') {
// this.downloadFileMsg(msg)
// this.testDownlod(msg)
} else {
var str = msg.attachments[0].image_url;
str = str.substring(1, ((str.length) - 1));
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
console.log(msg)
if (msg.file.type == "application/img") {
const modal = await this.modalController.create({
component: ViewMediaPage,
cssClass: 'modal modal-desktop',
componentProps: {
image: msg.attachments[0].image_url,
type: msg.file.type,
username: msg.u.name,
_updatedAt: msg._updatedAt
}
});
modal.present();
} else {
this.downloadFileFromBrowser("file", str)
this.downloadFileFromBrowser(msg.attachments[0].title, str)
this.downloadFileFromBrowser(msg.attachments[0].title, str)
}
} else {
if (msg.file.type == "application/img") {
const modal = await this.modalController.create({
component: ViewMediaPage,
cssClass: 'modal modal-desktop',
componentProps: {
image: msg.attachments[0].image_url,
type: msg.file.type,
username: msg.u.name,
_updatedAt: msg._updatedAt
}
});
modal.present();
} else {
this.openFile(msg.attachments[0].image_url, msg.attachments[0].title, msg.file.type);
}
}
}
}
}
imageSize(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);
}
// dataURItoBlobIso(dataURI: any) {
// const byteString = window.atob(dataURI);
// const arrayBuffer = new ArrayBuffer(byteString.length);
// const int8Array = new Uint8Array(arrayBuffer);
// for (let i = 0; i < byteString.length; i++) {
// int8Array[i] = byteString.charCodeAt(i);
// }
// const blob = new Blob([int8Array], { type: 'application/pdf' });
// return blob;
// }
messageDelete(message: MessageViewModal) {
this.chatServiceService.messageDelete({
messageId: message.id,
roomId: this.roomId,
})
}
async editMessage(message: any) {
const modal = await this.popoverController.create({
component: EditMessagePage,
cssClass: 'edit-message',
componentProps: {
message: message.message,
roomId: this.roomId,
}
});
modal.present()
return modal.onDidDismiss().then((res) => {
this.chatServiceService.updateMessage({
memberId: SessionStore.user.UserId,
message: res.data.message,
messageId: message.id,
requestId: '',
roomId: this.roomId
})
});
}
toggleEmojiPicker(message: MessageViewModal) {
if (this.selectedMessage === message) {
this.selectedMessage = null; // Close the picker if it's already open
} else {
this.selectedMessage = message; // Open the picker for the selected message
}
}
addReaction(message: any, emoji: string) {
// Logic to add reaction to the message
console.log(`Reacting to message ${message.id} with emoji ${emoji.codePointAt(0).toString(16)}`);
this.selectedMessage = null; // Close the picker after adding reaction
this.chatServiceService.reactToMessage({
memberId: SessionStore.user.UserId,
messageId: message.id,
roomId: this.roomId,
reaction: emoji,
requestId: ''
})
}
sendTyping() {
this.UserTypingRemoteRepositoryService.sendTyping(this.roomId)
}
}