Files
doneit-web/src/app/shared/chat/group-messages/group-messages.page.ts
T
Peter Maquiran 31f74933b7 remove alert
2023-02-22 09:31:14 +01:00

1127 lines
31 KiB
TypeScript

import { Component, OnChanges, OnInit, Input, SimpleChanges, Output, EventEmitter, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { AnimationController, ModalController, PopoverController, Platform } from '@ionic/angular';
import { AlertService } from 'src/app/services/alert.service';
import { ChatService } from 'src/app/services/chat.service';
import { ChatPopoverPage } from 'src/app/shared/popover/chat-popover/chat-popover.page';
import { GroupContactsPage } from './group-contacts/group-contacts.page';
import { ChatOptionsPopoverPage } from '../../popover/chat-options-popover/chat-options-popover.page';
import { ChatOptionsFeaturesPage } from 'src/app/modals/chat-options-features/chat-options-features.page';
import { TimeService } from 'src/app/services/functions/time.service';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList } from 'src/app/models/search-document';
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 { MessageService } from 'src/app/services/chat/message.service';
import { CameraService } from 'src/app/services/camera.service';
import { FileType } from 'src/app/models/fileType';
import { ToastService } from 'src/app/services/toast.service';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { VoiceRecorder, RecordingData, GenericResponse } from 'capacitor-voice-recorder';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { DomSanitizer } from '@angular/platform-browser';
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 { ViewMediaPage } from 'src/app/modals/view-media/view-media.page';
import { PermissionService } from 'src/app/services/permission.service';
@Component({
selector: 'app-group-messages',
templateUrl: './group-messages.page.html',
styleUrls: ['./group-messages.page.scss'],
})
export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy {
showLoader: boolean;
isGroupCreated: boolean;
loggedUser: any;
message: any;
messages: any;
allUsers: any[] = [];
documents: SearchList[] = [];
room: any = new Array();
roomName: any;
members: any;
capturedImage: any;
capturedImageTitle: any;
loggedUserChat: any;
scrollingOnce: boolean = true;
private scrollChangeCallback: () => void;
currentPosition: any;
startPosition: number;
scrollToBottomBtn = false;
roomCountDownDate: string;
roomCountDownTime: string;
isAdmin = false;
@Input() roomId: string;
@Output() closeAllDesktopComponents: EventEmitter<any> = new EventEmitter<any>();
@Output() showEmptyContainer: EventEmitter<any> = new EventEmitter<any>();
@Output() openGroupContacts: EventEmitter<any> = new EventEmitter<any>();
@Output() openEditGroupPage: EventEmitter<any> = new EventEmitter<any>();
@Output() openNewEventPage: EventEmitter<any> = new EventEmitter<any>();
@Output() getGroups: EventEmitter<any> = new EventEmitter<any>();
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
downloadFile: any;
showAvatar = false;
recording = false;
allowTyping = true;
storedFileNames = [];
lastAudioRecorded = '';
audioRecorded: any = "";
audioDownloaded: any = "";
durationDisplay = '';
duration = 0;
audioPermissionStatus: 'granted'| 'denied' | 'prompt' | null = null
sessionStore = SessionStore
groupNameFormart = "";
constructor(
public ChatSystemService: ChatSystemService,
private modalController: ModalController,
public popoverController: PopoverController,
private chatService: ChatService,
private animationController: AnimationController,
private alertService: AlertService,
private timeService: TimeService,
private fileService: FileService,
public ThemeService: ThemeService,
private storage: Storage,
private CameraService: CameraService,
private toastService: ToastService,
private sanitiser: DomSanitizer,
private file: File,
private platform: Platform,
private fileOpener: FileOpener,
public p: PermissionService,
) {
this.loggedUserChat = SessionStore.user.ChatData['data'];
this.isGroupCreated = true;
this.roomCountDownDate = "";
this.roomCountDownTime = "";
}
ngOnChanges(changes: SimpleChanges): void {
this.getRoomInfo();
this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({});
//
this.ChatSystemService.openRoom(this.roomId)
this.ChatSystemService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked
this.groupNameFormart = this.ChatSystemService.getGroupRoom(this.roomId).name.split('-').join(' ')
this.showAvatar = false
setTimeout(() => {
this.scrollToBottomClicked()
this.showAvatar = true
}, 50)
this.deleteRecording();
}
ngOnInit() {
// console.log(this.roomId)
this.loggedUser = this.loggedUserChat;
//setTimeout(() => {
this.getRoomInfo()
//}, 1000);
this.getChatMembers();
this.deleteRecording();
this.loadFiles();
}
showDateDuration(start: any) {
return this.timeService.showDateDuration(start);
}
countDownDate() {
return this.timeService.countDownDateTimer(this.roomCountDownDate, this.roomId);
}
setStatus(status: string) {
let body = {
message: '',
status: status,
}
this.chatService.setUserStatus(body).subscribe(res => {
//
})
}
scrollToBottom(): void {
try {
if (this.scrollingOnce) {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
}
} 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) => {
});
}
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) { }
}
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() {
window.removeEventListener('scroll', this.scrollChangeCallback, true);
}
async getChatMembers() {
this.chatService.getAllUsers().subscribe(res => {
//
this.allUsers = res['users'].filter(data => data.username != SessionStore.user.UserName);
//
});
}
openGroupContactsPage() {
this.openGroupContacts.emit(this.roomId);
}
openBookMeetingComponent() {
let data = {
roomId: this.roomId,
members: this.members
}
this.openNewEventPage.emit(data);
}
close() {
this.modalController.dismiss();
}
doRefresh(ev: any) {
this.getRoomInfo();
ev.target.complete();
}
get watch() {
this.getRoomInfo();
return this.roomId;
}
async getRoomInfo() {
if(this.ChatSystemService.getGroupRoom(this.roomId)) {
this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({});
}
let room = await this.chatService.getRoomInfo(this.roomId).toPromise();
// console.log('ROOM',room)
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;
}
this.getGroupContacts(this.room);
}
getGroupContacts(room: any) {
// this.showLoader = true;
// //If group is private call getGroupMembers
// if (room.t === 'p') {
// this.chatService.getGroupMembers(this.roomId).subscribe(res => {
// //
// this.members = res['members'];
// this.showLoader = false;
// });
// }
// //Otherwise call getChannelMembers for públic groups
// else {
// this.chatService.getChannelMembers(this.roomId).subscribe(res => {
// this.members = res['members'];
// this.showLoader = false;
// });
// }
this.members = this.ChatSystemService.getGroupRoom(this.roomId).members
}
sendMessage() {
this.ChatSystemService.getGroupRoom(this.roomId).send({})
}
base64toBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
async sendAudio(fileName) {
const roomId = this.roomId
let audioFile;
this.storage.get('recordData').then((recordData) => {
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}`;
}
//Converting base64 to blob
const encodedData = btoa(this.audioRecorded);
const blob = this.base64toBlob(encodedData, recordData.value.mimeType)
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getGroupRoom(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
})
});
this.deleteRecording();
}
deleteMessage(msgId: string) {
const room = this.ChatSystemService.getGroupRoom(this.roomId)
this.alertService.confirmDeleteMessage(msgId, room);
}
async openGroupMessagesOptions() {
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: ChatPopoverPage,
cssClass: 'model profile-modal search-submodal chat-aside',
componentProps: {
roomId: this.roomId,
members: this.members,
isAdmin: this.isAdmin
}
});
await modal.present();
modal.onDidDismiss().then(res => {
if (res.data == 'leave') {
this.getRoomInfo();
this.closeAllDesktopComponents.emit();
this.showEmptyContainer.emit();
this.ChatSystemService.hidingRoom(this.roomId).catch((error) => console.error(error));
}
else if (res.data == 'delete') {
this.closeAllDesktopComponents.emit();
this.showEmptyContainer.emit();
}
else if (res.data == 'cancel') {
}
else if (res.data == 'edit') {
//this.closeAllDesktopComponents.emit();
this.openEditGroupPage.emit(this.roomId);
}
else {
if(res?.data?.name) {
try {
this.roomName = res.data.name.split('-').join(' ');
} catch (error) {
console.log(error);
console.log(res.data)
this.roomName = res.data.name
}
}
};
});
}
openSendGroupMessageOptions(ev?: any) {
if (window.innerWidth <= 701) {
this.openChatOptions(ev);
}
else {
this._openChatOptions();
}
}
async openOptions(ev: any) {
const popover = await this.popoverController.create({
component: ChatPopoverPage,
cssClass: 'chat-popover modal-desktop',
event: ev,
componentProps: {
room: this.room,
},
translucent: true
});
await popover.present();
popover.onDidDismiss().then(res => {
if (res.data) {
//this.getRoomInfo();
//this.modalController.dismiss();
};
});
}
async openChatOptions(ev: any) {
const popover = await this.popoverController.create({
component: ChatOptionsPopoverPage,
cssClass: 'chat-options-popover',
event: ev,
componentProps: {
room: this.room,
members: this.members,
},
translucent: true
});
await popover.present();
await popover.onDidDismiss().then(() => {
});
}
async addContacts() {
const modal = await this.modalController.create({
component: GroupContactsPage,
componentProps: {
isCreated: this.isGroupCreated,
room: this.room,
members: this.members,
name: this.room.name,
},
cssClass: 'contacts',
backdropDismiss: false
});
await modal.present();
modal.onDidDismiss().then(() => {
//this.getRoomInfo();
});
}
async addDocGestaoDocumental() {
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 => {
if (res) {
const data = res.data;
this.documents.push(data.selected);
this.addFileWebtrix()
}
});
}
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);
}
}
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();
}
async takePictureMobile() {
const roomId = this.roomId
const file = await Camera.getPhoto({
quality: 90,
// allowEditing: true,
resultType: CameraResultType.Base64,
source: CameraSource.Camera
});
//const imageData = await this.fileToBase64Service.convert(file)
//
const response = await fetch('data:image/jpeg;base64,' + file.base64String!);
const blob = await response.blob();
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getGroupRoom(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,
}]
})
}
async takePicture() {
const roomId = this.roomId
const image = await this.CameraService.takePicture();
await this.fileService.saveImage(image)
const lastphoto: any = await this.fileService.loadFiles();
const { capturedImage, capturedImageTitle } = await this.fileService.loadFileData(lastphoto);
const base64 = await fetch(capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getGroupRoom(roomId).send({
file: {
"type": "application/img",
"guid": ''
},
attachments: [{
"title": capturedImageTitle,
"text": "description",
"title_link_download": false,
}],
temporaryData: formData
})
}
async addImage() {
this.addFileToChatMobile(['image/apng', 'image/jpeg', 'image/png'])
}
async addFile() {
this.addFileToChat(['.doc', '.docx', '.pdf'])
}
async addFileWebtrix() {
const roomId = this.roomId
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.ChatSystemService.getGroupRoom(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,
},
attachments: [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
// "title_link": url_no_options,
"title_link_download": true,
//"thumb_url": "assets/images/webtrix-logo.png",
// "message_link": url_no_options,
"type": "webtrix",
//"thumb_url": "assets/images/webtrix-logo.png",
"text": res.data.selected.DocTypeDesc,
"thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png",
}],
temporaryData: res
})
}
});
}
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)
//
const response = await fetch('data:image/jpeg;base64,' + file.base64String!);
const blob = await response.blob();
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getGroupRoom(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,
}]
})
}
async addFileToChat(types: typeof FileType[]) {
const roomId = this.roomId
const file: any = await this.fileService.getFileFromDevice(types);
if (file.type != "application/img" && file.type != "image/png" && file.type != "image/jpeg" && file.type != "image/gif") {
const encodedData = btoa(JSON.stringify(await this.getBase64(file).catch ((error) => {
console.error(error);
})));
const blob = this.base64toBlob(encodedData, file.type)
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getGroupRoom(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
})
} else {
}
}
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);
}
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,
members: this.members,
}
});
await modal.present();
modal.onDidDismiss().then(async (res) => {
const roomId = this.roomId;
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.takePicture()
}
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;
}
});
}
downloadFileMsg(msg: MessageService) {
msg.downloadFileMsg()
}
downloadFileFromBrowser(fileName: string, data: any): void {
const linkSource = data;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
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;
}
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)
//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)
}
} else {
this.openFile(str, msg.attachments[0].name, msg.file.type);
}
}
}
}
async audioPreview(msg) {
if (!msg.attachments[0].title_link || msg.attachments[0].title_link === null || msg.attachments[0].title_link === '') {
this.downloadFileMsg(msg)
} else { }
}
}