Files
doneit-web/src/app/ui/chat/modal/messages/messages.page.ts
T
2024-10-25 12:23:58 +01:00

1064 lines
29 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 { AlertService } from 'src/app/services/alert.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 { 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 { Subscription } from 'rxjs';
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 { compressImageBase64 } from 'src/app/utils/imageCompressore';
import { RecordingData } from 'capacitor-voice-recorder';
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 { RoomType } from "src/app/core/chat/entity/group";
import { MessageViewModal } from '../../store/model/message';
import { ChatPopoverPage } from '../chat-popover/chat-popover.page';
import { ViewOncesImagePageInput, ViewOncesImagePage } from '../view-onces/view-onces.page';
import { LastMessage } from '../../utils/lastMessage';
import { File } from '@awesome-cordova-plugins/file/ngx';
import { FileSystemMobileService } from 'src/app/infra/file-system/mobile/file-system-mobile.service';
import { RoomViewModel } from '../../store/model/room';
import { RoomStore } from '../../store/roomStore'
import { EditGroupPage } from '../edit-group/edit-group.page';
import { imageMimeTypes } from 'src/app/utils/allowedImageExtension';
import { GroupContactsPage, IGroupContactsPageOutPutSchema } from '../group-contacts/group-contacts.page';
@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;
scrollingOnce: boolean = true;
private scrollChangeCallback: () => void;
currentPosition: any;
startPosition: number;
scrollToBottomBtn = false;
showMessageOptions = false;
selectedMsgId: string;
LoadedDocument: any = null;
recording = false;
allowTyping = true;
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;
downloadProgess: number;
downloadLoader: boolean;
audioPermissionStatus: 'granted' | 'denied' | 'prompt' | null = null
sessionStore = SessionStore
SessionStore = SessionStore
selectedMessage: any = null;
emojis: string[] = ['😊', '😂', '❤️', '👍', '😢']; // Add more emojis as needed
textField = ''
MessageAttachmentFileType = MessageAttachmentFileType
MessageAttachmentFileSource = MessageAttachmentSource
messageOnReconnectSubject: Subscription
RoomTypeEnum = RoomType
IMessageType = IMessageType
handleClickActive = false
room!: RoomViewModel
constructor(
public popoverController: PopoverController,
private modalController: ModalController,
private navParams: NavParams,
private alertService: AlertService,
private toastService: ToastService,
private gestureController: GestureController,
public ThemeService: ThemeService,
private platform: Platform,
private storage: Storage,
private sanitiser: DomSanitizer,
private CameraService: CameraService,
private FilePickerMobileService: FilePickerMobileService,
private FilePickerWebService: FilePickerWebService,
private file: File,
private fileSystemMobileService: FileSystemMobileService,
public RoomStore: RoomStore,
) {
this.room = this.navParams.get('room');
this.RoomStore.start(this.room)
}
@HostListener('document:click', ['$event'])
@HostListener('document:touchstart', ['$event'])
handleClickOutside(event: Event) {
if (!this.handleClickActive) return;
const clickedInside = (event.target as HTMLElement).closest('.mat-menu-content');
setTimeout(()=> {
if (!clickedInside) {
this.selectedMessage = null;
}
}, 100);
}
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.RoomStore.totalMembers
}
allViewed(message: MessageViewModal) {
const totalMembers = this.RoomStore.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)
}
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();
}
doRefresh(ev: any) {
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) { }
}
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() {
this.RoomStore.stop()
window.removeEventListener('scroll', this.scrollChangeCallback, true);
this.handleClickActive = false; // Disable the listener before component destruction
}
async sendMessage() {
this.RoomStore.sendMessage(this.textField)
this.textField = ''
setTimeout(() => {
this.scrollToBottomClicked()
}, 100)
}
async sendAudio(fileName) {
const roomId = this.room.id
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
this.RoomStore.sendMessage('', [{
file: this.audioRecorded.split(',')[1],
fileName: "audio",
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Audio,
mimeType: audioMimeType, // 'audio/webm',
safeFile: this.sanitiser.bypassSecurityTrustResourceUrl(this.audioRecorded)
}])
setTimeout(() => {
this.scrollToBottomClicked()
}, 100)
this.deleteRecording();
});
this.deleteRecording();
}
viewDocument(file: any, url?: string) {
this.openViewDocumentModal(file);
}
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();
}
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.room.id,
members: [],
isAdmin: this.RoomStore.isAdmin,
roomType: this.RoomStore.room.roomType
},
cssClass: 'messages-options',
event: ev,
translucent: true,
});
await popover.present();
popover.onDidDismiss().then(res => {
if (res.data == 'leave') {
this.modalController.dismiss()
}
else if (res.data == 'delete') {
this.modalController.dismiss()
}
else if (res.data == 'cancel') {
this.modalController.dismiss()
}
else if (res.data == 'edit') {
//this.closeAllDesktopComponents.emit();
this.editGroup()
} else if (res.data == 'addUser') {
this.addContacts();
}
else {}
});
}
async addContacts() {
const modal = await this.modalController.create({
component: GroupContactsPage,
componentProps: {
roomId: this.RoomStore.room.id,
},
cssClass: 'contacts',
backdropDismiss: false
});
modal.onDidDismiss<IGroupContactsPageOutPutSchema>().then(result => {
// this.modalController.dismiss({roomId})
});
await modal.present();
}
async editGroup() {
const modal = await this.modalController.create({
component: EditGroupPage,
cssClass: 'modal modal-desktop',
componentProps: {
roomId: this.RoomStore.room.id,
},
});
await modal.present();
modal.onDidDismiss().then((res) => {
this.RoomStore.updateRoomDetails()
// this.getRoomInfo();
//this.modalController.dismiss(res.data);
});
}
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.room.id].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()) {
this.RoomStore.sendMessage('', [{
file: compressedImage.value.split(',')[1],
fileName: "foto",
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Image,
mimeType: 'image/'+picture.value.format
}])
}
}
}
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;
if (data.selected) {
this.RoomStore.sendMessage('', [{
fileName: res.data.selected.Assunto,
source: MessageAttachmentSource.Webtrix,
fileType: MessageAttachmentFileType.Doc,
applicationId: res.data.selected.ApplicationType,
docId: parseInt(res.data.selected.Id),
description: res.data.selected.Assunto
}])
}
});
}
async pickPicture() {
const result = await this.FilePickerMobileService.getFile({
types: imageMimeTypes,
multiple: false,
readData: true,
})
if(result.isOk()) {
const file = result.value.files[0]
if(file) {
let resultUrl = decodeURIComponent(file.path);
const base64 = await this.fileSystemMobileService.readFile({resultUrl})
if(base64.isOk()) {
// console.log('1', base64.value)
// console.log('base64.value.data', base64.value.data)
// console.log('file', file)
// console.log('3',createDataURL(base64.value.data, file.mimeType))
this.RoomStore.sendMessage('', [{
file: base64.value.data,
fileName: "foto",
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Image,
mimeType: file.mimeType
}])
} else {
console.log(base64.error)
}
} else {
console.log('no file')
}
} else {
console.log('error', result.error)
}
// 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()) {
// this.RoomStore.sendMessage('', [{
// file: compressedImage.value,
// fileName: "foto",
// source: MessageAttachmentSource.Device,
// fileType: MessageAttachmentFileType.Image,
// mimeType: 'image/'+file.value.format
// }])
// }
// }
// } 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.room.id
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)
this.RoomStore.sendMessage('', [{
file: result.value.files[0].data,
fileName: result.value.files[0].name,
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Doc,
description: result.value.files[0].name
}])
return
}
}
const file = await this.FilePickerWebService.getFileFromDevice(types)
if(file.isOk()) {
console.log(file)
const fileName = file.value.name
const validation = await allowedDocExtension(file.value.type)
if (validation.isOk()) {
let fileBase64 = await JSFileToDataUrl(file.value);
if(fileBase64.isOk()) {
this.RoomStore.sendMessage('', [{
file: fileBase64.value.split(',')[1],
fileName: file.value.name,
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Doc,
mimeType: file.value.type,
description: file.value.name
}])
}
} else {
console.log({fileName})
this.toastService._badRequest("Ficheiro inválido")
}
}
}
async openChatOptions(ev?: any) {
const roomId = this.room.id
const popover = await this.popoverController.create({
component: ChatOptionsPopoverPage,
cssClass: 'chat-options-popover',
event: ev,
componentProps: {
room: this.room.id,
members: this.RoomStore.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 fetchBlobFromURL(blobUrl: string): Promise<Blob> {
try {
const response = await fetch(blobUrl);
if (!response.ok) {
throw new Error(`Failed to fetch blob: ${response.statusText}`);
}
return await response.blob();
} catch (error) {
console.error('Error fetching blob from URL:', error);
throw error;
}
}
convertBlobToDataURL(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
if (reader.result) {
resolve(reader.result as string);
} else {
reject('Conversion failed');
}
};
reader.onerror = (error) => reject(error);
reader.readAsDataURL(blob);
});
}
async openFile(blobUrl:string, filename, fileType) {
let pathFile = ''
const fileName = filename
const contentFile = await this.fetchBlobFromURL(blobUrl)
if (this.platform.is('ios')) {
pathFile = this.file.documentsDirectory
} else {
pathFile = this.file.cacheDirectory
}
console.log(pathFile)
console.log(contentFile)
const writeResult = await this.fileSystemMobileService.writeFile(pathFile, fileName, contentFile, { replace: true })
if(writeResult.isOk()) {
const openResult = await this.fileSystemMobileService.fileOpener(pathFile + fileName, fileType)
}
}
downloadFileFromBrowser(fileName: string, msg: MessageViewModal): void {
if(msg.attachments[0]?.blobURl) {
// Create a temporary URL for the Blob
const url = msg.attachments[0].safeFile;
// Create an <a> element with the download attribute
const a = document.createElement('a');
a.href = url;
a.download = fileName; // Set the desired file name
a.click();
} else {
const link = document.createElement("a")
link.href = `data:${msg.attachments[0].mimeType}';base64,${msg.attachments[0].safeFile}`;
link.download = fileName
link.click()
link.remove()
}
}
async openPreview(msg: MessageViewModal) {
if (msg.attachments[0].source === MessageAttachmentSource.Webtrix) {
this.viewDocument(msg)
} else {
if (!msg.attachments[0].safeFile || msg.attachments[0].safeFile === null || msg.attachments[0].safeFile === '') {
} else {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
if (msg.attachments[0].mimeType.includes('image')) {
const modal = await this.modalController.create({
component: ViewMediaPage,
cssClass: 'modal modal-desktop',
componentProps: {
image: msg.attachments[0].safeFile,
type: msg.attachments[0].mimeType,
username: msg.attachments[0].description,
_updatedAt: msg.sentAt
}
});
modal.present();
} else {
this.downloadFileFromBrowser(msg.attachments[0].description, msg)
}
} else {
if (msg.attachments[0].mimeType.includes('image')) {
const modal = await this.modalController.create({
component: ViewMediaPage,
cssClass: 'modal modal-desktop',
componentProps: {
image: msg.attachments[0].safeFile,
type: msg.attachments[0].mimeType,
username: msg.attachments[0].description,
_updatedAt: msg.sentAt
}
});
modal.present();
} else {
this.openFile(msg.attachments[0].safeFile, msg.attachments[0].fileName || msg.attachments[0].description, msg.attachments[0].mimeType);
}
}
}
}
}
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);
}
messageDelete(message: MessageViewModal) {
this.RoomStore.messageDelete(message)
}
async editMessage(message: any) {
const modal = await this.popoverController.create({
component: EditMessagePage,
cssClass: 'edit-message',
componentProps: {
message: message.message,
roomId: this.room.id,
}
});
modal.present()
return modal.onDidDismiss().then((res) => {
if(res.data) {
this.RoomStore.updateMessage({
messageId:message.id,
message: res.data.message
})
}
});
}
toggleEmojiPicker(message: MessageViewModal) {
if (this.selectedMessage === message) {
this.selectedMessage = null; // Close the picker if it's already open
} else {
this.handleClickActive = true
this.selectedMessage = message; // Open the picker for the selected message
}
}
addReaction(message: any, emoji: string) {
console.log('reaction==')
// Logic to add reaction to the message
this.selectedMessage = null; // Close the picker after adding reaction
this.RoomStore.addReaction(message, emoji)
}
sendTyping() {
this.RoomStore.sendTyping()
}
}