improve chat

This commit is contained in:
Peter Maquiran
2024-08-17 22:05:57 +01:00
parent eb615d4335
commit 650c772084
43 changed files with 712 additions and 1540 deletions
+152 -314
View File
@@ -1,14 +1,11 @@
import { AfterViewInit, Component, ElementRef, 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 { EventPerson } from 'src/app/models/eventperson.model';
import { ExpedientTaskModalPageNavParamsTask } from 'src/app/models/ExpedientTaskModalPage';
import { ContactsPage } from 'src/app/ui/chat/modal/messages/contacts/contacts.page';
import { AlertService } from 'src/app/services/alert.service';
import { FileService } from 'src/app/services/functions/file.service';
import { ToastService } from 'src/app/services/toast.service';
import { ChatMessageStore } from 'src/app/store/chat/chat-message.service';
import { ChatUserStorage } from 'src/app/store/chat/chat-user.service';
import { ThemeService } from 'src/app/services/theme.service'
import { VoiceRecorder, GenericResponse } from 'capacitor-voice-recorder';
@@ -16,15 +13,11 @@ import { Haptics, ImpactStyle } from '@capacitor/haptics';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { SearchPage } from 'src/app/pages/search/search.page';
import { Storage } from '@ionic/storage';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
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 { File } from '@awesome-cordova-plugins/file/ngx';
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { FileValidatorService } from "src/app/services/file/file-validator.service"
import { FilePicker } from '@capawesome/capacitor-file-picker';
//======
import { Observable as DexieObservable } from 'Dexie';
import { Subscription } from 'rxjs';
@@ -45,7 +38,11 @@ import { RecordingData } from 'capacitor-voice-recorder';
import { Logger } from 'src/app/services/logger/main/service';
import { MessagesOptionsPage } from '../messages-options/messages-options.page';
import { ChatOptionsPopoverPage } from '../chat-options-popover/chat-options-popover.page';
import { CameraService } from 'src/app/infra/camera/camera.service'
import { FilePickerMobileService } from 'src/app/infra/file-picker/mobile/file-picker-mobile.service'
import { FilePickerWebService } from 'src/app/infra/file-picker/web/file-picker-web.service'
import { allowedDocExtension } from 'src/app/utils/allowedDocExtension';
import { JSFileToDataUrl } from 'src/app/utils/ToBase64';
const IMAGE_DIR = 'stored-images';
@Component({
@@ -57,7 +54,6 @@ 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
@@ -70,15 +66,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
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;
@@ -146,14 +137,14 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
private platform: Platform,
private storage: Storage,
private sanitiser: DomSanitizer,
private file: File,
private fileOpener: FileOpener,
private FileValidatorService: FileValidatorService,
private roomRepositoryService: RoomRepositoryService,
private messageRepositoryService: MessageRepositoryService,
private userTypingServiceRepository: UserTypingServiceRepository,
private chatServiceService: ChatServiceService,
private FilePickerService: FilePickerService,
private CameraService: CameraService,
private FilePickerMobileService: FilePickerMobileService,
private FilePickerWebService: FilePickerWebService
) {
@@ -169,23 +160,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.listenToSendMessage()
this.roomMessage$ = this.messageRepositoryService.getItemsLive(this.roomId)
// this.roomMessage$ = this.messageRepositoryService.getItemsLive(this.roomId)
this.roomMembers$ = this.roomRepositoryService.getRoomMemberByIdLive(this.roomId) as any
this.roomStatus$ = this.roomRepositoryService.getRoomStatus(this.roomId)
this.roomRepositoryService.getRoomById(this.roomId)
this.newMessagesStream?.unsubscribe()
this.newMessagesStream = this.messageRepositoryService.subscribeToNewMessages(this.roomId).subscribe((e) => {
setTimeout(() => {
this.scrollToBottomClicked()
}, 200)
setTimeout(() => {
this.scrollToBottomClicked()
}, 500)
})
// this.roomRepositoryService.getRoomById(this.roomId)
this.userTypingServiceRepository.getUserTypingLive().subscribe((e) => {
const arrayNames = e.map(e => e.userName)
@@ -218,10 +196,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
for(const message of this.messages1[this.roomId]) {
if(message.hasAttachment) {
const result = await this.chatServiceService.getMessageAttachmentByMessageId({
$messageId: message.$id,
id: message.attachments[0].id
})
const result = await this.chatServiceService.getMessageAttachmentByMessageId(message)
if(result.isOk()) {
@@ -282,14 +258,11 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
listenToIncomingMessage() {
this.messageReceiveSubject?.unsubscribe();
this.messageReceiveSubject = this.chatServiceService.listenToIncomingMessage(this.roomId).subscribe(async (message) => {
this.messages1[this.roomId].push(message as MessageEntity)
this.messages1[this.roomId].unshift(message as MessageEntity)
if(message.hasAttachment) {
const result = await this.chatServiceService.getMessageAttachmentByMessageId({
$messageId: message.$id,
id: message.attachments[0].id
})
const result = await this.chatServiceService.getMessageAttachmentByMessageId(message)
if(result.isOk()) {
@@ -734,33 +707,48 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
async takePictureMobile() {
this.addFileToChatMobile()
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
)
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]);
if(compressedImage.isOk()) {
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
const message = new MessageEntity();
message.roomId = this.roomId
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
// create a view into the buffer
var ia = new Uint8Array(ab);
message.attachments = [{
file: compressedImage.value.split(',')[1],
fileName: "foto",
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Image,
mimeType: 'image/'+picture.value.format
}]
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message)
}
// 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;
}
@@ -856,6 +844,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
} 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
})
@@ -863,79 +854,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
async addFileToChatMobile() {
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) {
console.log('add file ')
@@ -944,100 +862,90 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
if (this.platform.is('ios')) {
console.log('ios add file ')
const resultt = await FilePicker.pickFiles({
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,
});
})
console.log('RESULT', resultt.files[0].data)
if(result.isOk()) {
console.log('RESULT', result.value.files[0].data)
const message = new MessageEntity();
message.roomId = this.roomId
const message = new MessageEntity();
message.roomId = this.roomId
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.attachments = [{
file: result.value.files[0].data,
fileName: result.value.files[0].name,
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Doc
}]
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message)
return
}
message.attachments = [{
file: resultt.files[0].data,
fileName: resultt.files[0].name,
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Doc
}]
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message)
return
}
const file = await this.fileService.getFileFromDevice(types);
console.log(file)
const file = await this.FilePickerWebService.getFileFromDevice(types)
if(file.isOk()) {
console.log(file)
const fileName = file.name
const fileName = file.value.name
const validation = this.FileValidatorService.fileNameValidation(fileName)
const validation = await allowedDocExtension(fileName)
if (validation.isOk) {
if (validation.isOk()) {
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)
let fileBase64 = await JSFileToDataUrl(file.value);
const formData = new FormData();
formData.append('blobFile', blob);
if(fileBase64.isOk()) {
const message = new MessageEntity();
message.roomId = this.roomId
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
}
message.attachments = [{
file: fileBase64.value.split(',')[1],
fileName: file.value.name,
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Doc,
mimeType: file.value.type
}]
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message)
}
const message = new MessageEntity();
message.roomId = this.roomId
message.sender = {
userPhoto: '',
wxeMail: SessionStore.user.Email,
wxFullName: SessionStore.user.FullName,
wxUserId: SessionStore.user.UserId
} else {
this.toastService._badRequest("Ficheiro inválido")
}
message.attachments = [{
file: encodedData,
fileName: file.name,
source: MessageAttachmentSource.Device,
fileType: MessageAttachmentFileType.Doc,
mimeType: file.type
}]
this.messages1[this.roomId].push(message)
this.chatServiceService.sendMessage(message)
} else {
this.toastService._badRequest("Ficheiro inválido")
}
}
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
@@ -1085,40 +993,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
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;
}
blobToBase64(blob) {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
async openFile(pdfString, filename, type) {
console.log('url while open ',pdfString)
@@ -1135,43 +1009,43 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
/*
await modal.present(); */
var blob = new Blob([pdfString], { type: 'application/pdf' });
// var blob = new Blob([pdfString], { type: 'application/pdf' });
console.log('blob blob', blob)
// console.log('blob blob', blob)
this.blobToBase64(blob).then((value) => {
console.log(value)
}).catch((error) => {
console.log(error)
})
// this.blobToBase64(blob).then((value) => {
// console.log(value)
// }).catch((error) => {
// console.log(error)
// })
let pathFile = ''
const fileName = filename
if (this.platform.is('ios')) {
pathFile = this.file.documentsDirectory
} else {
pathFile = this.file.externalRootDirectory
}
// let pathFile = ''
// const fileName = filename
// if (this.platform.is('ios')) {
// pathFile = this.file.documentsDirectory
// } else {
// pathFile = this.file.externalRootDirectory
// }
console.log('file data', pdfString)
console.log(pathFile)
// console.log('file data', pdfString)
// console.log(pathFile)
let removePre = this.removeTextBeforeSlash(pdfString,',')
console.log('file data remove ', removePre)
// let removePre = this.removeTextBeforeSlash(pdfString,',')
// console.log('file data remove ', removePre)
await Filesystem.writeFile({
path: fileName,
data: removePre,
directory: Directory.Cache,
}).then((dir) => {
console.log('DIR ', dir)
this.fileOpener
.open(dir.uri, type)
.then(() => console.log())
.catch(e => console.error(e))
}).catch((error) => {
console.log('error writing the file', error)
});
// await Filesystem.writeFile({
// path: fileName,
// data: removePre,
// directory: Directory.Cache,
// }).then((dir) => {
// console.log('DIR ', dir)
// this.fileOpener
// .open(dir.uri, type)
// .then(() => console.log())
// .catch(e => console.error(e))
// }).catch((error) => {
// console.log('error writing the file', error)
// });
}
removeTextBeforeSlash(inputString, controlString) {
@@ -1273,52 +1147,16 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
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);
};
});
}
dataURItoBlobIso(dataURI: any) {
const byteString = window.atob(dataURI);
const arrayBuffer = new ArrayBuffer(byteString.length);
const int8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
int8Array[i] = byteString.charCodeAt(i);
}
const blob = new Blob([int8Array], { type: 'application/pdf' });
return blob;
}
// dataURItoBlobIso(dataURI: any) {
// const byteString = window.atob(dataURI);
// const arrayBuffer = new ArrayBuffer(byteString.length);
// const int8Array = new Uint8Array(arrayBuffer);
// for (let i = 0; i < byteString.length; i++) {
// int8Array[i] = byteString.charCodeAt(i);
// }
// const blob = new Blob([int8Array], { type: 'application/pdf' });
// return blob;
// }
messageDelete(message: MessageEntity) {