fix merge

This commit is contained in:
Peter Maquiran
2022-04-07 14:40:37 +01:00
30 changed files with 1554 additions and 603 deletions
@@ -37,6 +37,8 @@ import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { DomSanitizer } from '@angular/platform-browser';
import { MessageService } from 'src/app/services/chat/message.service';
import { AlertController } from '@ionic/angular';
import { File } from '@awesome-cordova-plugins/file/ngx';
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';
@Component({
selector: 'app-group-messages',
@@ -81,8 +83,8 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
allowTyping = true;
storedFileNames = [];
lastAudioRecorded = '';
audioRecorded:any = "";
audioDownloaded:any = "";
audioRecorded: any = "";
audioDownloaded: any = "";
durationDisplay = '';
duration = 0;
showAvatar = true;
@@ -113,7 +115,9 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
private processesService: ProcessesService,
private CameraService: CameraService,
private sanitiser: DomSanitizer,
private alertController: AlertController
private alertController: AlertController,
private file: File,
private fileOpener: FileOpener,
) {
this.loggedUserChat = authService.ValidatedUserChat['data'];
this.isGroupCreated = true;
@@ -164,9 +168,9 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
message: '',
status: status,
}
this.chatService.setUserStatus(body).subscribe(res => {
console.log(res);
})
// this.chatService.setUserStatus(body).subscribe(res => {
// console.log(res);
// })
}
deleteMessage(msgId: string) {
@@ -227,7 +231,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}, 1000)
}
async getFile(fileName?:any){
async getFile(fileName?: any) {
const audioFile = await Filesystem.readFile({
path: fileName,
directory: Directory.Data
@@ -257,14 +261,14 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
try {
this.storage.get('recordData').then((recordData) => {
console.log(recordData);
if(recordData?.value?.recordDataBase64.includes('data:audio')){
if (recordData?.value?.recordDataBase64.includes('data:audio')) {
this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(recordData?.value?.recordDataBase64);
}
else{
else {
this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(`data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`);
}
});
} catch (error) {}
} catch (error) { }
}
@@ -278,7 +282,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
this.recording = false;
VoiceRecorder.stopRecording().then(async (result: RecordingData) => {
console.log('==================================',result);
console.log('==================================', result);
this.recording = false;
if (result.value && result.value.recordDataBase64) {
@@ -286,8 +290,8 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
//console.log(recordData);
const fileName = new Date().getTime() + ".mp3";
//Save file
await this.storage.set('fileName',fileName)
this.storage.set('recordData',result).then(() => {
await this.storage.set('fileName', fileName)
this.storage.set('recordData', result).then(() => {
console.log('Audio recorded saved', result);
setTimeout(async () => {
@@ -346,7 +350,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
async deleteRecording(){
async deleteRecording() {
this.storage.remove('fileName');
this.storage.remove('recordData');
@@ -397,15 +401,15 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
getRoomInfo() {
this.showLoader = true;
this.chatService.getRoomInfo(this.roomId).subscribe(room => {
this.room = room['room'];
this.roomName = this.room.name.split('-').join(' ');
if (this.room.customFields.countDownDate) {
this.roomCountDownDate = this.timeService.countDownDateTimer(this.room.customFields.countDownDate, this.room._id);
}
this.getGroupContacts(this.room);
this.showLoader = false;
});
// this.chatService.getRoomInfo(this.roomId).subscribe(room => {
// this.room = room['room'];
// this.roomName = this.room.name.split('-').join(' ');
// if (this.room.customFields.countDownDate) {
// this.roomCountDownDate = this.timeService.countDownDateTimer(this.room.customFields.countDownDate, this.room._id);
// }
// this.getGroupContacts(this.room);
// this.showLoader = false;
// });
}
async getChatMembers() {
@@ -481,17 +485,17 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
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);
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) {
@@ -500,35 +504,35 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.storage.get('recordData').then((recordData) => {
console.log(recordData);
audioFile = recordData;
if(recordData?.value?.recordDataBase64.includes('data:audio')){
if (recordData?.value?.recordDataBase64.includes('data:audio')) {
this.audioRecorded = recordData?.value?.recordDataBase64;
}
else{
else {
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)
console.log(blob)
const formData = new FormData();
formData.append("blobFile", blob);
//Converting base64 to blob
const encodedData = btoa(this.audioRecorded);
const blob = this.base64toBlob(encodedData, recordData.value.mimeType)
console.log(blob)
const formData = new FormData();
formData.append("blobFile", blob);
this.wsChatMethodsService.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.wsChatMethodsService.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();
}
@@ -710,6 +714,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
},
temporaryData: res,
attachments: [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
@@ -729,37 +734,60 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
async addFileToChat(types: typeof FileType[] ) {
async addFileToChat(types: typeof FileType[]) {
const roomId = this.roomId
const file: any = await this.fileService.getFileFromDevice(types);
console.log('Add file', file)
/* const imageData = await this.fileToBase64Service.convert(file).then((filee) => {
console.log('Add file', filee)
}) */
const response = await fetch(file);
const blob = await response.blob();
console.log('Add file', blob)
const formData = new FormData();
formData.append("blobFile", blob);
console.log('Add file', JSON.stringify(await this.getBase64(file)))
this.wsChatMethodsService.getGroupRoom(roomId).send({
file: {
"type": file.type,
"guid": '',
},
attachments: [{
"title": file.name ,
"name": file.name ,
// "text": "description",
//"image_url": file.base64String, // rocketchat
"title_link_download": false,
}],
temporaryData: formData
})
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)));
const blob = this.base64toBlob(encodedData, file.type)
console.log('Add Blob file', blob)
const formData = new FormData();
formData.append('blobFile', blob);
console.log(formData)
this.wsChatMethodsService.getGroupRoom(roomId).send({
file: {
"type": file.type,
"guid": '',
},
attachments: [{
"title": file.name,
"name": file.name,
// "text": "description",
"title_link_download": false,
}],
temporaryData: formData
});
} else {
console.log('File type invalid')
}
}
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) {
console.log('Error: ', error);
};
});
}
@@ -1017,27 +1045,99 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
card.el.style['z-index'] = 11;
}
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) {
const blob = this.b64toBlob(pdfString, 'application/pdf')
let pathFile = ''
const fileName = filename
const contentFile = blob
if (this.platform.is('ios')) {
pathFile = this.file.documentsDirectory
} else {
pathFile = this.file.externalRootDirectory
}
console.log(pdfString)
console.log(pathFile)
console.log(contentFile)
this.file
.writeFile(pathFile, fileName, contentFile, { replace: true })
.then(success => {
this.fileOpener
.open(pathFile + fileName, 'application/pdf')
.then(() => console.log('File is opened'))
.catch(e => console.log('Error opening file', e));
})
.catch(e => console.log('Error writing file', e))
}
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();
}
async openPreview(msg: MessageService) {
if (!msg.attachments[0].image_url ||msg.attachments[0].image_url === null || msg.attachments[0].image_url === '') {
this.downloadFileMsg(msg)
if(msg.file.type === "application/webtrix") {
this.viewDocument(msg.file, msg.attachments.image_url)
} else {
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
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')) {
this.downloadFileFromBrowser(msg.attachments[0].name, str)
/* const modal = await this.modalController.create({
component: ViewMediaPage,
cssClass: 'modal modal-desktop',
componentProps: {
image: str,
type: msg.file.type,
username: msg.u.name,
_updatedAt: msg._updatedAt
}
});
modal.present(); */
} else {
this.openFile(str, msg.attachments[0].name);
}
});
modal.present();
}
}
}
@@ -1046,7 +1146,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
console.log(msg);
if (!msg.attachments[0].title_link || msg.attachments[0].title_link === null || msg.attachments[0].title_link === '') {
this.downloadFileMsg(msg)
} else {}
} else { }
}
}
@@ -12,7 +12,6 @@ import { BtnModalDismissPage } from 'src/app/shared/btn-modal-dismiss/btn-modal-
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { MatMenuModule } from '@angular/material/menu';
import { LettersAvatarModule } from "ngx-letters-avatar";
import { PipesModule } from 'src/app/pipes/pipes.module';
@NgModule({
imports: [
@@ -23,7 +22,6 @@ import { PipesModule } from 'src/app/pipes/pipes.module';
MessagesPageRoutingModule,
MatMenuModule,
LettersAvatarModule,
PipesModule,
],
declarations: [MessagesPage]
})
@@ -90,10 +90,10 @@
</div>
<div *ngIf="msg.file.type != 'application/img'">
<div class="file add-attachment-bg-color" *ngIf="msg.file.type != 'application/audio'">
<div (click)="docIndex(i); viewDocument(msg, file.title_link)"
class="file-details add-ellipsis cursor-pointer" *ngIf="msg.file">
<div (click)="docIndex(i); openPreview(msg)" class="file-details add-ellipsis cursor-pointer" *ngIf="msg.file">
<span *ngIf="msg.file.type">
<fa-icon *ngIf="msg.file.type == 'application/pdf'" icon="file-pdf" class="pdf-icon"></fa-icon>
<fa-icon *ngIf="msg.file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'" icon="file-word" class="word-icon"></fa-icon>
<fa-icon *ngIf="msg.file.type == 'application/word'" icon="file-word" class="word-icon">
</fa-icon>
<fa-icon
+218 -144
View File
@@ -20,7 +20,7 @@ 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 { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { Directory, Encoding, Filesystem, FilesystemDirectory, } from '@capacitor/filesystem';
import { VoiceRecorder, VoiceRecorderPlugin, RecordingData, GenericResponse, CurrentRecordingStatus } from 'capacitor-voice-recorder';
import { Haptics, ImpactStyle } from '@capacitor/haptics';
import { PreviewCameraPage } from 'src/app/modals/preview-camera/preview-camera.page';
@@ -40,10 +40,16 @@ import { SearchPage } from 'src/app/pages/search/search.page';
import { Storage } from '@ionic/storage';
import { FileToBase64Service } from 'src/app/services/file/file-to-base64.service';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Plugins, Capacitor } from '@capacitor/core';
import { MultipleDocumentsPicker } from '@awesome-cordova-plugins/multiple-document-picker/ngx';
import { DomSanitizer } from '@angular/platform-browser';
/* import {Plugins} from '@capacitor/core';
import { StringDecoder } from 'string_decoder';
import { File } from '@awesome-cordova-plugins/file/ngx';
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';
import { DocumentViewer } from '@awesome-cordova-plugins/document-viewer/ngx';
const { Filesystem } = Plugins; */
const IMAGE_DIR = 'stored-images';
@Component({
selector: 'app-messages',
@@ -87,14 +93,20 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
allowTyping = true;
storedFileNames = [];
lastAudioRecorded = '';
audioRecorded:any = "";
audioDownloaded:any = "";
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;
audioPermissionStatus: 'granted'| 'denied' | 'prompt' | null = null
@@ -123,8 +135,13 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
private processesService: ProcessesService,
private storage: Storage,
private fileToBase64Service: FileToBase64Service,
private multipleDocumentsPicker: MultipleDocumentsPicker,
private sant: DomSanitizer,
private file: File,
private fileOpener: FileOpener,
private sanitiser: DomSanitizer,
private alertController: AlertController
private alertController: AlertController,
private document: DocumentViewer
) {
this.loggedUser = authService.ValidatedUserChat['data'];
this.roomId = this.navParams.get('roomId');
@@ -212,16 +229,16 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
try {
this.storage.get('recordData').then((recordData) => {
console.log(recordData);
if(recordData?.value?.recordDataBase64.includes('data:audio')){
if (recordData?.value?.recordDataBase64.includes('data:audio')) {
this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(recordData?.value?.recordDataBase64);
}
else{
else {
this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(`data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`);
}
});
} catch (error) {}
} catch (error) { }
}
@@ -267,6 +284,11 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
await alertPopup.present();
}
this.recording = true;
VoiceRecorder.startRecording()
.then((result: GenericResponse) => console.log(result.value))
.catch(error => console.log(error));
this.calculateDuration();
}
stopRecording() {
@@ -285,8 +307,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
//console.log(recordData);
const fileName = new Date().getTime() + ".mp3";
//Save file
this.storage.set('fileName',fileName);
this.storage.set('recordData',result).then(() => {
this.storage.set('fileName', fileName);
this.storage.set('recordData', result).then(() => {
console.log('Audio recorded saved');
})
}
@@ -296,7 +318,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}, 1000);
}
async deleteRecording(){
async deleteRecording() {
this.storage.remove('fileName');
this.storage.remove('recordData');
@@ -415,17 +437,17 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
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);
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
@@ -433,92 +455,48 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.storage.get('recordData').then((recordData) => {
audioFile = recordData;
if(recordData?.value?.recordDataBase64) {
if(recordData.value.recordDataBase64.includes('data:audio')){
this.audioRecorded = recordData.value.recordDataBase64;
}
else{
this.audioRecorded = `data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`;
}
console.log(this.audioRecorded);
//Converting base64 to blob
const encodedData = btoa(this.audioRecorded);
const blob = this.base64toBlob(encodedData, recordData.value.mimeType)
console.log(blob)
const formData = new FormData();
formData.append("blobFile", blob);
this.wsChatMethodsService.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
})
} else {
alert('no audio')
if (recordData?.value?.recordDataBase64.includes('data:audio')) {
this.audioRecorded = recordData?.value?.recordDataBase64;
}
else {
this.audioRecorded = `data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`;
}
console.log(this.audioRecorded);
});
//Converting base64 to blob
const encodedData = btoa(this.audioRecorded);
const blob = this.base64toBlob(encodedData, recordData.value.mimeType)
console.log(blob)
const formData = new FormData();
formData.append("blobFile", blob);
this.wsChatMethodsService.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
})
});
this.deleteRecording();
}
blobToBase64 = blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise(resolve => {
reader.onloadend = () => {
resolve(reader.result);
};
});
};
viewDocument(msg: any, url?: string) {
console.log(msg)
if (msg.attachments.type == "application/webtrix") {
//this.openViewDocumentModal(file);
viewDocument(file: any, url?: string) {
console.log()
if (file.type == "application/webtrix") {
this.openViewDocumentModal(file);
}
if (msg.attachments.type == "application/pdf") {
try {
const writeSecretFile = async () => {
await Filesystem.writeFile({
path: msg.attachments.name,
data: msg.attachments.image_url,
directory: Directory.Documents,
encoding: Encoding.UTF8,
});
};
console.log('WRITE', writeSecretFile);
const readSecretFile = async () => {
const contents = await Filesystem.readFile({
path: msg.attachments.name,
directory: Directory.Documents,
encoding: Encoding.UTF8,
});
console.log('secrets:', contents);
};
console.log('READ', readSecretFile);
} catch (e) {
console.error("Unable to write file", e);
}
else {
let fullUrl = "https://www.tabularium.pt" + url;
this.fileService.viewDocumentByUrl(fullUrl);
}
}
@@ -751,6 +729,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
},
temporaryData: res,
attachments: [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
@@ -801,37 +780,62 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
getFileReader(): FileReader {
const fileReader = new FileReader();
const zoneOriginalInstance = (fileReader as any)["__zone_symbol__originalInstance"];
return zoneOriginalInstance || fileReader;
}
async addFileToChat(types: typeof FileType[]) {
const roomId = this.roomId
const file: any = await this.fileService.getFileFromDevice(types);
console.log('Add file', file)
/* const imageData = await this.fileToBase64Service.convert(file).then((filee) => {
console.log('Add file', filee)
}) */
const blob = new Blob(file, { type: file.type })
console.log('Add file', blob)
const formData = new FormData();
formData.append("blobFile", blob);
console.log('Add file', JSON.stringify(await this.getBase64(file)))
this.wsChatMethodsService.getDmRoom(roomId).send({
file: {
"type": file.type,
"guid": '',
},
attachments: [{
"title": file.name,
"name": file.name,
// "text": "description",
"title_link_download": false,
}],
temporaryData: formData
})
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)));
const blob = this.base64toBlob(encodedData, file.type)
console.log('Add Blob file', blob)
const formData = new FormData();
formData.append('blobFile', blob);
console.log(formData)
this.wsChatMethodsService.getDmRoom(roomId).send({
file: {
"type": file.type,
"guid": '',
},
attachments: [{
"title": file.name,
"name": file.name,
// "text": "description",
"title_link_download": false,
}],
temporaryData: formData
});
} else {
console.log('File type invalid')
}
}
getBase64(file) {
var reader = this.getFileReader();
reader.readAsDataURL(file);
return new Promise(resolve => {
reader.onload = function () {
resolve(reader.result)
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
});
}
@@ -949,39 +953,109 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
testeDownload(msg: MessageService) {
this.downloadFile = "";
this.AttachmentsService.downloadFileAndStore(msg.file.guid);
}
/* testeDownload(msg: MessageService) {
this.downloadFile = "";
this.AttachmentsService.downloadFileAndStore(msg.file.guid);
} */
downloadFileMsg(msg: MessageService) {
msg.downloadFileMsg()
msg.downloadFileMsg();
}
testDownlod(msg: MessageService) {
this.AttachmentsService.downloadFileAndStore(msg.file.guid)
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
}
console.log(pdfString)
console.log(pathFile)
console.log(contentFile)
this.file
.writeFile(pathFile, fileName, contentFile, { replace: true })
.then(success => {
this.fileOpener
.open(pathFile + fileName, type)
.then(() => console.log('File is opened'))
.catch(e => console.log('Error opening file', e));
})
.catch(e => console.log('Error writing file', 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) {
console.log(msg);
if (!msg.attachments[0].image_url || msg.attachments[0].image_url === null || msg.attachments[0].image_url === '' || !msg.attachments[0].title_link || msg.attachments[0].title_link === null || msg.attachments[0].title_link === '') {
this.downloadFile(msg)
//this.testDownlod(msg)
if(msg.file.type === "application/webtrix") {
this.viewDocument(msg.file, msg.attachments.image_url)
} else {
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
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')) {
this.downloadFileFromBrowser(msg.attachments[0].name, str)
/* const modal = await this.modalController.create({
component: ViewMediaPage,
cssClass: 'modal modal-desktop',
componentProps: {
image: str,
type: msg.file.type,
username: msg.u.name,
_updatedAt: msg._updatedAt
}
});
modal.present(); */
} else {
this.openFile(str, msg.attachments[0].name, msg.file.type);
}
});
modal.present();
}
}
}
@@ -990,7 +1064,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
console.log(msg);
if (!msg.attachments[0].title_link || msg.attachments[0].title_link === null || msg.attachments[0].title_link === '') {
this.downloadFileMsg(msg)
} else {}
} else { }
}