Files
doneit-web/src/app/pages/chat/messages/messages.page.ts
T
2023-10-19 15:03:12 +01:00

1243 lines
34 KiB
TypeScript

import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router'
import { GestureController, ModalController, NavParams, PopoverController, Platform, AlertController } from '@ionic/angular';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { EventPerson } from 'src/app/models/eventperson.model';
import { ExpedientTaskModalPageNavParamsTask } from 'src/app/models/ExpedientTaskModalPage';
import { ContactsPage } from 'src/app/pages/chat/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 { 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 { ChatMessageStore } from 'src/app/store/chat/chat-message.service';
import { ChatUserStorage } from 'src/app/store/chat/chat-user.service';
import { environment } from 'src/environments/environment';
import { ThemeService } from 'src/app/services/theme.service'
import { VoiceRecorder, RecordingData, GenericResponse } from 'capacitor-voice-recorder';
import { Haptics, ImpactStyle } from '@capacitor/haptics';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { ChatSystemService } from 'src/app/services/chat/chat-system.service'
import { MessageService } from 'src/app/services/chat/message.service';
import { FileType } from 'src/app/models/fileType';
import { SearchPage } from 'src/app/pages/search/search.page';
import { Storage } from '@ionic/storage';
import { Camera, CameraResultType, CameraSource } 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 { File } from '@awesome-cordova-plugins/file/ngx';
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { NewEventPage } from '../../agenda/new-event/new-event.page';
import { NotificationsService } from 'src/app/services/notifications.service';
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'
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('messageContainer') messageContainer: ElementRef; */
@ViewChild('rectangle') private rectangle: ElementRef;
canvas: any
ctx: any
loggedUser: any;
userPresence = '';
dmUsers: any;
roomId: string;
el: any;
members: any;
scrollingOnce: boolean = true;
chatMessageStore = ChatMessageStore;
chatUserStorage = ChatUserStorage;
private scrollChangeCallback: () => void;
currentPosition: any;
startPosition: number;
scrollToBottomBtn = false;
attendees: EventPerson[] = [];
longPressActive = 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;
//items: File[] = [];
fileSelected?: Blob;
pdfUrl?: string;
base64File: string;
downloadProgess: number;
downloadLoader: boolean;
audioPermissionStatus: 'granted' | 'denied' | 'prompt' | null = null
sessionStore = SessionStore
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,
public ChatSystemService: ChatSystemService,
private storage: Storage,
//private fileOpener: FileOpener,
private sanitiser: DomSanitizer,
// private document: DocumentViewer
private file: File,
private fileOpener: FileOpener,
private router: Router,
public RochetChatConnectorService: RochetChatConnectorService,
) {
try {
this.loggedUser = SessionStore.user.ChatData['data'];
this.roomId = this.navParams.get('roomId');
window.onresize = (event) => {
if (window.innerWidth > 701) {
this.modalController.dismiss();
}
}
this.ChatSystemService.getDmRoom(this.roomId).loadHistory({})
this.ChatSystemService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked
this.ChatSystemService.openRoom(this.roomId)
setTimeout(() => {
this.scrollToBottomClicked()
}, 150)
} catch (error) {
//alert(error)
}
}
ngOnInit() {
try {
console.log(this.router.url);
this.createDirectoryImage()
// this.chatService.refreshtoken();
this.ChatSystemService.getUserOfRoom(this.roomId).then((value) => {
}).catch((error) => {
console.error(error)
})
this.getChatMembers();
} catch (error) {
//alert(error)
}
}
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) {
const room = this.ChatSystemService.getDmRoom(this.roomId)
this.alertService.confirmDeleteMessage(msgId, room);
}
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);
}
sendMessage() {
this.ChatSystemService.getDmRoom(this.roomId).send({}).then(() => {
})
}
/* sendMessage(msg) {
let lastMsg = msg.pop();
console.log(msg)
console.log(lastMsg._id,lastMsg.u.username,lastMsg.msg)
this.ChatSystemService.getDmRoom(this.roomId).send({}).then(() => {
if(lastMsg.u.username == this.members[1].username) {
this.notificationService.ChatSendMessageNotification(this.members[0].username,this.members[1].name,lastMsg.msg,this.roomId)
} else if (msg.u.username == this.members[0].username) {
this.notificationService.ChatSendMessageNotification(this.members[1].username,this.members[1].name,lastMsg.msg,this.roomId)
}
})
} */
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 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.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();
}
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() {
// 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
}
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: MessagesOptionsPage,
componentProps: {
roomId: this.roomId,
},
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 bookMeeting() {
let attendees = this.ChatSystemService.getDmRoom(this.roomId).members.map((val) => {
return {
Name: val.name,
EmailAddress: val.username + "@" + environment.domain,
IsRequired: "true",
}
});
this.popoverController.dismiss();
if (window.innerWidth <= 1024) {
const modal = await this.modalController.create({
component: NewEventPage,
componentProps: {
attendees: attendees,
roomId: this.roomId
},
cssClass: 'modal modal-desktop',
backdropDismiss: false
});
modal.onDidDismiss().then((data) => {
if (data?.data && data.data.id) {
// const roomId = this.roomId
// this.ChatSystemService.getDmRoom(roomId).send({
// file: {
// "type": "application/meeting",
// "subject": data.data.Subject,
// "start_date": data.data.StartDate,
// "end_date": data.data.EndDate,
// "venue": data.data.venue,
// "id": data.data.id,
// "calendarId": data.data.CalendarId
// },
// temporaryData: {}
// })
}
});
await modal.present();
}
}
async takePicture() {
const roomId = this.roomId
const file = await Camera.getPhoto({
quality: 90,
// allowEditing: true,
resultType: CameraResultType.Base64,
source: CameraSource.Camera
});
var imageBase64 = 'data:image/jpeg;base64,' + file.base64String
const compressedImage = await this.compressImageBase64(
imageBase64,
800, // maxWidth
800, // maxHeight
0.9 // quality
).then((picture) => {
console.log('Selected: ', picture)
imageBase64 = picture
});
console.log(imageBase64)
const blob = this.dataURItoBlob(imageBase64)
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getDmRoom(roomId).send({
file: {
"type": "application/img",
"guid": ''
},
attachments: [{
"title": "file.jpg",
"text": "description",
"title_link_download": false,
}],
temporaryData: formData,
attachmentsModelData: {
fileBase64: imageBase64,
}
})
}
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 addImageMobile() {
this.addFileToChatMobile(['image/apng', 'image/jpeg', 'image/png'])
}
async addImage() {
this.addFileToChat(['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,
}
});
await modal.present();
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": url_no_options,
"title_link_download": true,
"thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png",
// "message_link": url_no_options,
"text": res.data.selected.DocTypeDesc,
"type": "webtrix"
}],
})
}
});
}
async addFileToChatMobile(types: typeof FileType[]) {
console.log('add image from gallery')
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)
//
var imageBase64 = 'data:image/jpeg;base64,' + file.base64String
const compressedImage = await this.compressImageBase64(
imageBase64,
800, // maxWidth
800, // maxHeight
0.9 // quality
).then((picture) => {
console.log('Selected: ', picture)
imageBase64 = picture
});
console.log(imageBase64)
const response = await fetch(imageBase64);
const blob = await response.blob();
const formData = new FormData();
console.log('add file', formData)
formData.append("blobFile", blob);
console.log('add file', formData)
this.ChatSystemService.getDmRoom(roomId).send({
file: {
"type": "application/img",
"guid": ''
},
temporaryData: formData,
attachments: [{
"title": file.path,
"text": "description",
"title_link_download": false,
}],
attachmentsModelData: {
fileBase64: imageBase64,
}
})
}
getFileReader(): FileReader {
const fileReader = new FileReader();
const zoneOriginalInstance = (fileReader as any)["__zone_symbol__originalInstance"];
return zoneOriginalInstance || fileReader;
}
_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);
};
})
}
async addFileToChat(types: typeof FileType[]) {
console.log('add file')
const roomId = this.roomId
const file: any = await this.fileService.getFileFromDevice(types);
console.log(file)
/* const encodedData = btoa(JSON.stringify(await this.getBase64(file).catch ((error) => {
console.error(error);
})));
const blob = this.fileService.base64toBlob(encodedData, file.type)
const fileBase64 = await this._getBase64(file)
const formData = new FormData();
formData.append('blobFile', blob);
console.log('add file', fileBase64) */
if (file.type != "application/img" && file.type != "image/png" && file.type != "image/jpeg" && file.type != "image/gif") {
console.log('TYPE', file.type)
const encodedData = btoa(JSON.stringify(await this.getBase64(file).catch((error) => {
console.error(error);
})));
console.log(encodedData)
const blob = this.fileService.base64toBlob(encodedData, file.type)
console.log('BLOB BLOB', blob)
const formData = new FormData();
formData.append('blobFile', blob);
/* console.log('add file', fileBase64) */
this.ChatSystemService.getDmRoom(roomId).send({
file: {
"type": file.type,
"guid": '',
},
attachments: [{
"title": file.name,
"name": file.name,
// "text": "description",
"title_link_download": false,
}],
temporaryData: formData,
attachmentsModelData: {
fileBase64: encodedData,
}
});
} else {
console.log('file not supported')
}
}
getBase64(file) {
var reader = this.getFileReader();
reader.readAsDataURL(file);
return new Promise(resolve => {
reader.onload = function () {
resolve(reader.result)
};
reader.onerror = function (error) {
};
});
}
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'] == 'meeting') {
this.bookMeeting();
}
else if (res['data'] == 'take-picture') {
this.takePicture()
}
else if (res['data'] == 'add-picture') {
console.log('add-picture')
this.addImageMobile()
}
else if (res['data'] == 'add-document') {
this.addFile()
}
else if (res['data'] == 'documentoGestaoDocumental') {
this.addFileWebtrix()
}
});
}
// getRoomMessageDB(roomId) {
// if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
// } else {
// this.sqlservice.getAllChatMSG(roomId).then((msg: any) => {
// let chatmsgArray = [];
// msg.forEach(element => {
// let msgChat = {
// _id: element.Id,
// attachments: this.isJson(element.Attachments),
// channels: this.isJson(element.Channels),
// file: this.isJson(element.File),
// mentions: this.isJson(element.Mentions),
// msg: element.Msg,
// rid: element.Rid,
// ts: element.Ts,
// u: this.isJson(element.U),
// _updatedAt: element.UpdatedAt,
// image_url: this.isJson(element.image_url)
// }
// chatmsgArray.push(msgChat)
// });
// })
// }
// }
isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return "";
}
return JSON.parse(str);
}
transformDataMSG(res) {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
} else {
res.forEach(element => {
let chatmsg = {
_id: element._id,
attachments: element.attachments,
channels: element.channels,
file: element.file,
mentions: element.mentions,
msg: element.msg,
rid: element.rid,
ts: element.ts,
u: element.u,
_updatedAt: element._updatedAt,
/* image_url: {
name: name,
path: `${IMAGE_DIR}/${name}`,
data: `data:image/jpeg;base64,${readFile.data}`,
}, */
}
// this.sqlservice.addChatMSG(chatmsg)
});
}
}
/* testeDownload(msg: MessageService) {
this.downloadFile = "";
this.AttachmentsService.downloadFileAndStore(msg.file.guid);
} */
downloadFileMsg(msg: MessageService) {
msg.downloadFileMsg();
}
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;
}
async openFile(pdfString, filename, type) {
const blob = this.b64toBlob(pdfString, type)
console.log(blob)
let pathFile = ''
const fileName = filename
const contentFile = blob
if (this.platform.is('ios')) {
pathFile = this.file.documentsDirectory
} else {
pathFile = this.file.externalRootDirectory
}
console.log(pathFile)
await Filesystem.writeFile({
path: fileName,
data: pdfString,
directory: Directory.Data,
}).then((dir) => {
console.log('DIR ', dir)
this.fileOpener
.open(dir.uri, type)
.then(() => console.log())
.catch(e => console.error(e))
});
}
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(str, msg.attachments[0].title, 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 { }
}
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);
}
// async ShareEmail(msg){
// // Check if sharing via email is supported
// await Share.share({
// title: msg.u.username,
// text: msg._updatedAt,
// url: msg.attachments[0].image_url,
// dialogTitle: 'Share with buddies',
// });
// }
async createDirectoryImage() {
await Filesystem.mkdir({
path: IMAGE_DIR,
directory: Directory.Data,
recursive: true
});
}
async compressImageBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> {
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);
};
});
}
}