import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core'; import { AnimationController, GestureController, IonRange, ModalController, PopoverController } from '@ionic/angular'; 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 { ChatOptionsFeaturesPage } from 'src/app/modals/chat-options-features/chat-options-features.page'; import { ChatMessageStore } from 'src/app/store/chat/chat-message.service'; import { ChatUserStorage } from 'src/app/store/chat/chat-user.service'; import { TimeService } from 'src/app/services/functions/time.service'; import { FileService } from 'src/app/services/functions/file.service'; import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page'; import { ThemeService } from 'src/app/services/theme.service'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; import { Storage } from '@ionic/storage'; import { ChatSystemService } from 'src/app/services/chat/chat-system.service' import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service' import { MessageService } from 'src/app/services/chat/message.service'; import { CameraService } from 'src/app/services/camera.service'; import { FileType } from 'src/app/models/fileType'; import { SearchPage } from 'src/app/pages/search/search.page'; import { Camera, CameraResultType, CameraSource } from '@capacitor/camera'; import { DocumentViewer, DocumentViewerOptions } from '@ionic-native/document-viewer'; import { VoiceRecorder, RecordingData, GenericResponse } from 'capacitor-voice-recorder'; import { Filesystem, Directory } from '@capacitor/filesystem'; import { DomSanitizer } from '@angular/platform-browser'; import { Platform } from '@ionic/angular'; import { File } from '@awesome-cordova-plugins/file/ngx'; import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx'; import { SessionStore } from 'src/app/store/session.service'; import { Howl } from 'howler'; import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { ChatMessageDebuggingPage } from 'src/app/shared/popover/chat-message-debugging/chat-message-debugging.page'; import { PermissionService } from 'src/app/services/permission.service'; import { FileValidatorService } from "src/app/services/file/file-validator.service" const IMAGE_DIR = 'stored-images'; @Component({ selector: 'app-messages', templateUrl: './messages.page.html', styleUrls: ['./messages.page.scss'], }) export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy { showLoader: boolean; @ViewChild('scrollMe') private myScrollContainer: ElementRef; @ViewChild('message-item') messageContainer: ElementRef; messages: any; dm: any; userPresence = ''; dmUsers: any; checktimeOut: boolean; members: any; downloadProgess = 0; @Input() roomId: string; @Input() showMessages: string; @Output() openNewEventPage: EventEmitter = new EventEmitter(); @Output() getDirectMessages: EventEmitter = new EventEmitter(); chatMessageStore = ChatMessageStore chatUserStorage = ChatUserStorage scrollingOnce: boolean = true; private scrollChangeCallback: () => void; currentPosition: any; startPosition: number; mesageItemDropdownOptions: boolean = false; scrollToBottomBtn = false; longPressActive = false; frameUrl: any; downloadFile: string; massages: MessageService[] = [] showAvatar = true; recording = false; allowTyping = true; storedFileNames = []; lastAudioRecorded = ''; audioRecorded: any = ""; audioDownloaded: any = ""; durationDisplay = ''; duration = 0; audioPermissionStatus: 'granted' | 'denied' | 'prompt' | null = null sessionStore = SessionStore audioPlay: Howl = null; isPlaying = false; audioProgress = 0; audioDuration = 0; audioTimer: any; @ViewChild('range', { static: false }) range: IonRange; userName = ""; room: any = new Array(); roomName: any; isAdmin = false; roomCountDownDate: string; constructor( public popoverController: PopoverController, private modalController: ModalController, /* private navParams: NavParams, */ private chatService: ChatService, private animationController: AnimationController, private toastService: ToastService, private timeService: TimeService, private fileService: FileService, private gestureController: GestureController, public ThemeService: ThemeService, private storage: Storage, public ChatSystemService: ChatSystemService, public RochetChatConnectorService: RochetChatConnectorService, private CameraService: CameraService, private sanitiser: DomSanitizer, private file: File, private platform: Platform, private fileOpener: FileOpener, public p: PermissionService, private FileValidatorService: FileValidatorService ) { // update this.checkAudioPermission() } ngOnChanges(changes: SimpleChanges): void { this.ChatSystemService.getAllRooms(); this.ChatSystemService.getDmRoom(this.roomId).loadHistory({}) this.ChatSystemService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked this.ChatSystemService.openRoom(this.roomId) this.showAvatar = false setTimeout(() => { this.scrollToBottomClicked() this.showAvatar = true }, 150) this.deleteRecording() // this.ChatSystemService.getDmRoom(this.roomId).deleteAll() } async ChatMessageDebuggingPage() { const modal = await this.modalController.create({ component: ChatMessageDebuggingPage, cssClass: 'model profile-modal search-submodal', componentProps: { roomId: this.roomId, } }); return await modal.present(); } async checkAudioPermission() { const permissionStatus = await navigator.permissions.query({ name: 'microphone' } as any) this.audioPermissionStatus = permissionStatus.state permissionStatus.onchange = (data: any) => { // // } } ngOnInit() { this.ChatSystemService.getAllRooms(); // this.chatService.refreshtoken(); this.scrollToBottom(); this.getChatMembers(); this.deleteRecording(); this.loadFiles(); } onPressingMessage() { const gesture = this.gestureController.create({ el: this.messageContainer.nativeElement, gestureName: 'long-press', onStart: ev => { this.longPressActive = true; }, onEnd: ev => { this.longPressActive = false; } }); } load = () => { this.checktimeOut = true; this.getChatMembers(); } doRefresh(ev: any) { this.load(); ev.target.complete(); } scrollToBottom = () => { 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; //this.scrollingOnce = false; } catch (err) { } } ngAfterViewInit() { this.scrollChangeCallback = () => this.onContentScrolled(event); window.addEventListener('scroll', this.scrollChangeCallback, true); } 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; } 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 getFile(fileName?: any) { const audioFile = await Filesystem.readFile({ path: fileName, directory: Directory.Data }) const base64sound = audioFile.data; const base64Response = await fetch(`data:audio/ogg;base64,${base64sound}`); this.audioRecorded = base64Response.url; } async loadFiles() { try { this.storage.get('fileName').then((fileName) => { this.lastAudioRecorded = fileName; }) 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) { } 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}`); } }); } 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(); } ngOnDestroy() { this.checktimeOut = false; window.removeEventListener('scroll', this.scrollChangeCallback, true); } openBookMeetingComponent() { let data = { roomId: this.roomId, members: this.members } this.openNewEventPage.emit(data); } showDateDuration(start: any) { return this.timeService.showDateDuration(start); } 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, }); modal.onDidDismiss().then((res) => { }); await modal.present(); } sendMessage() { this.ChatSystemService.getDmRoom(this.roomId).send({}) } async sendAudio(fileName) { const roomId = this.roomId let audioFile; this.storage.get('recordData').then(async (recordData) => { audioFile = recordData; if (recordData?.value?.recordDataBase64?.includes('data:audio')) { this.audioRecorded = recordData.value.recordDataBase64; } else { this.audioRecorded = `data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`; } //Converting base64 to blob const encodedData = btoa(this.audioRecorded); const blob = this.fileService.base64toBlob(encodedData, recordData.value.mimeType) const formData = new FormData(); formData.append("blobFile", blob); this.ChatSystemService.getDmRoom(roomId).send({ file: { "type": "application/audio", "msDuration": audioFile.value.msDuration, "mimeType": audioFile.value.mimeType, }, attachments: [{ "title": fileName, "title_link_download": true, "type": "audio" }], temporaryData: formData, attachmentsModelData: { fileBase64: encodedData, } }) }); this.deleteRecording(); } deleteMessage(msgId: string, msg: MessageService) { this.ChatSystemService.getDmRoom(this.roomId).sendDeleteRequest(msgId) } async openViewDocumentModal(file: any) { let task = { serialNumber: '', taskStartDate: '', isEvent: true, workflowInstanceDataFields: { FolderID: '', Subject: file.Assunto, SourceSecFsID: file.ApplicationId, SourceType: 'DOC', 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() { // // this.showLoader = true; // this.chatService.getMembers(this.roomId).subscribe(res => { // this.members = res['members']; // this.dmUsers = res['members'].filter(data => data.username != this.sessionStore.user.UserName) // this.showLoader = false; // }); this.members = this.ChatSystemService.getDmRoom(this.roomId).members this.dmUsers = this.ChatSystemService.getDmRoom(this.roomId).membersExcludeMe } 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 }); modal.onDidDismiss(); await modal.present(); } openSendMessageOptions(ev?: any) { if (window.innerWidth < 701) { this.openChatOptions(ev); } else { 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 modal = await this.modalController.create({ enterAnimation, leaveAnimation, component: MessagesOptionsPage, cssClass: 'model profile-modal search-submodal', componentProps: { roomId: this.roomId, } }); return await modal.present(); } dataURItoBlob(dataURI) { // convert base64 to raw binary data held in a string // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this var byteString = atob(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); // create a view into the buffer var ia = new Uint8Array(ab); // set the bytes of the buffer to the correct values for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } // write the ArrayBuffer to a blob, and you're done var blob = new Blob([ab], { type: mimeString }); return blob; } async takePictureMobile() { const roomId = this.roomId const file = await Camera.getPhoto({ quality: 90, // allowEditing: true, resultType: CameraResultType.Base64, source: CameraSource.Camera }); console.log('Selected: ', file) var base64 = 'data:image/jpeg;base64,' + file.base64String const compressedImage = await this.compressImageBase64( base64, 800, // maxWidth 800, // maxHeight 0.9 // quality ).then((picture) => { base64 = picture }); const blob = this.dataURItoBlob(base64) const formData = new FormData(); formData.append("blobFile", blob); this.ChatSystemService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', }, temporaryData: formData, attachments: [{ "title": file.path, // "image_url": "", //"image_url": 'data:image/jpeg;base64,' + file.base64String, "text": "description", "title_link_download": false, }], attachmentsModelData: { fileBase64: base64, } }) } async takePicture() { const roomId = this.roomId const file = await Camera.getPhoto({ quality: 90, // allowEditing: true, resultType: CameraResultType.Base64, source: CameraSource.Camera }); console.log('FILE CHAT',file) const imageBase64 = 'data:image/jpeg;base64,' + file.base64String const blob = this.dataURItoBlob(imageBase64) console.log(imageBase64) const formData = new FormData(); formData.append("blobFile", blob); this.ChatSystemService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '' }, temporaryData: formData, attachments: [{ "title": "file.jpg", "text": "description", "title_link_download": false, }], attachmentsModelData: { fileBase64: imageBase64, } }) } async addImage() { this.addFileToChatMobile(['image/apng', 'image/jpeg', 'image/png']) } 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, } }); modal.onDidDismiss().then(async res => { const data = res.data; const roomId = this.roomId if (data.selected) { this.ChatSystemService.getDmRoom(roomId).send({ file: { "name": res.data.selected.Assunto, "type": "application/webtrix", "ApplicationId": res.data.selected.ApplicationType, "DocId": res.data.selected.Id, "Assunto": res.data.selected.Assunto, }, temporaryData: res, attachments: [{ "title": res.data.selected.Assunto, "description": res.data.selected.DocTypeDesc, "title_link_download": true, "type": "webtrix", "text": res.data.selected.DocTypeDesc, "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", }], }) } }); await modal.present(); } async addFileToChatMobile(types: typeof FileType[]) { const roomId = this.roomId const file = await Camera.getPhoto({ quality: 90, // allowEditing: true, resultType: CameraResultType.Base64, source: CameraSource.Photos }); //const imageData = await this.fileToBase64Service.convert(file) // console.log('Selected: ', file) var base64 = 'data:image/jpeg;base64,' + file.base64String if (file.format == "jpeg" || file.format == "png" || file.format == "gif") { const compressedImage = await this.compressImageBase64( base64, 800, // maxWidth 800, // maxHeight 0.9 // quality ).then((picture) => { base64 = picture }); const response = await fetch(base64); const blob = await response.blob(); console.log(base64) const formData = new FormData(); formData.append("blobFile", blob); this.ChatSystemService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '' }, temporaryData: formData, attachments: [{ "title": file.path, //"image_url": 'data:image/jpeg;base64,' + file.base64String, "text": "description", "title_link_download": false, }], attachmentsModelData: { fileBase64: base64, } }) } } async addFileToChat(types: typeof FileType[]) { const roomId = this.roomId const file: any = await this.fileService.getFileFromDevice(types); if (file.type == 'application/pdf' || file.type == 'application/doc' || file.type == 'application/docx' || file.type == 'application/xls' || file.type == 'application/xlsx' || file.type == 'application/ppt' || file.type == 'application/pptx' || file.type == 'application/txt') { console.log('FILE', file) const fileName = file.name const validation = this.FileValidatorService.fileNameValidation(fileName) if (validation.isOk) { const encodedData = btoa(JSON.stringify(await this.getBase64(file).catch((error) => { console.error(error); }))); let blob; let formData let fileBase64 if (this.platform.is("tablet")) { blob = this.fileService.base64toBlob(encodedData, file.type) console.log('BLOB BLOB', blob) formData = new FormData(); formData.append('blobFile', file); /* console.log('add file', fileBase64) */ } else { blob = this.fileService.base64toBlob(encodedData, file.type) fileBase64 = await this._getBase64(file) formData = new FormData(); formData.append('blobFile', file); } this.ChatSystemService.getDmRoom(roomId).send({ file: { "type": file.type, "guid": '', }, attachments: [{ "title": file.name, "name": file.name, //"image_url": res, // "text": "description", "title_link_download": false, }], temporaryData: formData, attachmentsModelData: { fileBase64: fileBase64, } }) } else { this.toastService._badRequest("Ficheiro inválido") } } } _getBase64(file) { return new Promise((resolve, reject) => { var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { resolve(reader.result) }; reader.onerror = function (error) { console.log('Error: ', error); }; }) } getFileReader(): FileReader { const fileReader = new FileReader(); const zoneOriginalInstance = (fileReader as any)["__zone_symbol__originalInstance"]; return zoneOriginalInstance || fileReader; } getBase64(file) { var reader = this.getFileReader(); reader.readAsDataURL(file); return new Promise(resolve => { reader.onload = function () { resolve(reader.result) }; reader.onerror = function (error) { }; }); } bookMeeting() { let data = { roomId: this.roomId, members: this.members } this.openNewEventPage.emit(data); } chatsend() { } async _openChatOptions() { const roomId = this.roomId; 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, members: this.members, } }); modal.onDidDismiss().then(async (res) => { if (res['data'] == 'meeting') { //this.closeAllDesktopComponents.emit(); let data = { roomId: this.roomId, members: this.members } this.openNewEventPage.emit(data); } else if (res['data'] == 'take-picture') { this.takePictureMobile() } else if (res['data'] == 'add-picture') { this.addImage() } else if (res['data'] == 'add-document') { this.addFile() } else if (res['data'] == 'documentoGestaoDocumental') { this.addFileWebtrix() this.showLoader = false; } }); await modal.present(); } downloadFileMsg(msg: MessageService) { msg.downloadFileMsg() } pdfPreview() { const options: DocumentViewerOptions = { title: 'My App' }; DocumentViewer.viewDocument } async audioPreview(msg) { if (!msg.attachments[0].title_link || msg.attachments[0].title_link === null || msg.attachments[0].title_link === '') { this.downloadFileMsg(msg) } else { } } b64toBlob(b64Data, contentType) { contentType = contentType || ''; var sliceSize = 512; b64Data = b64Data.replace(/^[^,]+,/, ''); b64Data = b64Data.replace(/\s/g, ''); var byteCharacters = window.atob(b64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } var blob = new Blob(byteArrays, { type: contentType }); return blob; } downloadFileFromBrowser(fileName: string, data: any): void { const linkSource = data; const downloadLink = document.createElement("a"); downloadLink.href = linkSource; downloadLink.download = fileName; downloadLink.click(); } 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); } } openFile(pdfString, filename, type) { const blob = this.b64toBlob(pdfString, type) let pathFile = '' const fileName = filename const contentFile = blob if (this.platform.is('ios')) { pathFile = this.file.documentsDirectory } else { pathFile = this.file.externalRootDirectory } this.file .writeFile(pathFile, fileName, contentFile, { replace: true }) .then(success => { this.fileOpener .open(pathFile + fileName, type) .then(() => { }) .catch(e => console.error(e)) }) .catch(e => console.error(e)) } 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) } else { var str = msg.attachments[0].image_url str = str.substring(1, ((str.length) - 1)); if (this.platform.is('desktop') || this.platform.is('mobileweb')) { 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) } } else { this.openFile(str, msg.attachments[0].title, msg.file.type); // this.downloadFileFromBrowser("file", str) } } } } start(track) { if (this.audioPlay) { this.audioPlay.stop(); } this.audioPlay = new Howl({ src: [track.changingThisBreaksApplicationSecurity], onplay: () => { this.isPlaying = true; this.updateProgress() }, onend: () => { this.isPlaying = false; clearTimeout(this.audioTimer) this.audioProgress = 0 }, }) this.audioPlay.play(); } togglePlayer(pause) { this.isPlaying = !pause; if (pause) { this.audioPlay.pause(); } else { this.audioPlay.play(); } } seek() { let newValue = +this.range.value; let duration = this.audioPlay.duration(); this.audioPlay.seek(duration * (newValue / 100)); } updateProgress() { let seek = this.audioPlay.seek(); this.audioProgress = (seek / this.audioPlay.duration()) * 100 || 0; this.audioTimer = setTimeout(() => { this.updateProgress() }, 1000) } async getRoomInfo() { let room = await this.chatService.getRoomInfo(this.roomId).toPromise(); this.room = room['room']; if (this.room.name) { try { this.roomName = this.room.name.split('-').join(' '); } catch (error) { this.roomName = this.room.name; } } if (SessionStore.user.ChatData.data.userId == this.room.u._id) { this.isAdmin = true } else { this.isAdmin = false } if (this.room.customFields.countDownDate) { this.roomCountDownDate = this.room.customFields.countDownDate; } } async compressImageBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise { return new Promise((resolve, reject) => { const image = new (window as any).Image(); image.src = base64String; image.onload = async () => { const canvas = document.createElement('canvas'); let newWidth = image.width; let newHeight = image.height; if (newWidth > maxWidth) { newHeight *= maxWidth / newWidth; newWidth = maxWidth; } if (newHeight > maxHeight) { newWidth *= maxHeight / newHeight; newHeight = maxHeight; } canvas.width = newWidth; canvas.height = newHeight; const context = canvas.getContext('2d'); context?.drawImage(image, 0, 0, newWidth, newHeight); const compressedBase64 = canvas.toDataURL('image/jpeg', quality); resolve(compressedBase64); }; image.onerror = (error) => { reject(error); }; }); } }