This commit is contained in:
Peter Maquiran
2022-02-07 13:41:27 +01:00
17 changed files with 1120 additions and 1107 deletions
+65 -469
View File
@@ -1,21 +1,13 @@
import { Injectable } from '@angular/core';
import { FileLoaderService } from '../file/file-loader.service';
import { FileToBase64Service } from '../file/file-to-base64.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ChatService } from '../chat.service';
import { ModalController, Platform,LoadingController } from '@ionic/angular';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList } from 'src/app/models/search-document';
import { ProcessesService } from '../processes.service';
import { ToastService } from '../toast.service';
import { Camera, CameraResultType, CameraSource, Photo} from '@capacitor/camera';
import { LoadingController, Platform } from '@ionic/angular';
import {Photo} from '@capacitor/camera';
import { FileType } from 'src/app/models/fileType';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpEventType, HttpHeaders, HttpParams } from '@angular/common/http';
import { Storage } from '@ionic/storage';
const IMAGE_DIR = 'stored-images';
import { FileToBase64Service } from 'src/app/services/file/file-to-base64.service';
const IMAGE_DIR = 'stored-images';
interface LocalFile {
name: string;
@@ -31,112 +23,24 @@ export class FileService {
images: LocalFile[] = [];
capturedImage:any;
capturedImageTitle:any;
documents:SearchList[] = [];
showLoader: boolean;
files: Set<File>;
photos: any[] = [];
idroom: any;
headers: HttpHeaders;
downloadProgess = 0;
downloadFilename: any;
convertBlobToBase64Worker;
constructor(
private fileLoaderService: FileLoaderService,
private fileToBase64Service: FileToBase64Service,
private iab: InAppBrowser,
private chatService: ChatService,
private modalController: ModalController,
private processesService: ProcessesService,
private toastService: ToastService,
private platform: Platform,
private loadingCtrl: LoadingController,
private http: HttpClient,
private storage: Storage
) {
this.headers = new HttpHeaders();
}
private platform: Platform,
private fileToBase64Service: FileToBase64Service
) {}
uploadFile(formData:any){
console.log('UPLOAD file', formData)
//const geturl = environment.apiURL + 'Tasks/DelegateTask';
const geturl = environment.apiURL + 'ObjectServer/UploadFiles';
let options = {
headers: this.headers
};
return this.http.post(`${geturl}`, formData, options);
}
getFile(guid:any){
const geturl = environment.apiURL + 'lakefs/StreamFile';
let params = new HttpParams();
params = params.set("path", guid);
this.headers = this.headers.set('responseType', 'blob');
this.headers = this.headers.set('Content-Type', 'application/octet-stream');
let options = {
headers: this.headers,
params: params
};
return this.http.get<any>(`${geturl}`, options);
}
downloadFile(guid:any) {
let downloadUrl = environment.apiURL +'objectserver/streamfiles?path='+guid;
var name = new Date().getTime();
return this.http.get(downloadUrl, {
responseType: "arraybuffer",
reportProgress: true, observe: 'events'
})
}
_arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
async takePicture() {
const capturedImage = await Camera.getPhoto({
quality: 90,
// allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Camera
});
const response = await fetch(capturedImage.webPath!);
const blob = await response.blob();
this.photos.unshift({
filepath: "soon...",
webviewPath: capturedImage.webPath
});
this.capturedImage = await this.convertBlobToBase64(blob);
this.capturedImageTitle = new Date().getTime() + '.jpeg';
let data = {
image:this.capturedImage,
name: this.capturedImageTitle
}
return data;
}
convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader;
@@ -147,68 +51,9 @@ export class FileService {
reader.readAsDataURL(blob);
});
async loadPicture(roomid) {
const capturedImage = await Camera.getPhoto({
quality: 90,
// allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Photos
});
const response = await fetch(capturedImage.webPath!);
const blob = await response.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.uploadFile(formData).toPromise()
console.log(guid.path);
this.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
let body = {
"message":
{
"rid": roomid,
"msg": "",
"attachments": [{
"title": this.capturedImageTitle,
"title_link_download": false,
"image_url": fileImage,
}],
"file":{
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
}
}
}
console.log('BODY TAKE PICTURE CHAT', body)
const loader = this.toastService.loading();
this.chatService.sendMessage(body).subscribe(res=> {
console.log(res);
loader.remove();
},(error) => {
loader.remove();
this.toastService.badRequest("Não foi possível adicionar a fotografia!");
});
});
}
});
}
//new method1
async saveImage(photo: Photo, roomid: any) {
async saveImage(photo: Photo) {
const base64Data = await this.readAsBase64(photo);
const fileName = new Date().getTime() + '.jpeg';
@@ -217,10 +62,43 @@ export class FileService {
data: base64Data,
directory: Directory.Data
});
this.loadFiles(roomid);
}
//new method 3
async loadFiles() {
const loading = await this.loadingCtrl.create({
message: 'Loading data...',
});
await loading.present();
return new Promise((resolve, reject)=>{
Filesystem.readdir({
path: IMAGE_DIR,
directory: Directory.Data,
}).then(result => {
console.log('ALL RESULTS', result.files[0])
let lastphoto = result.files[result.files.length - 1]
resolve(lastphoto)
},
async (err) => {
console.log('ERROR FILE DOSENT EXIST', err)
reject('ERROR FILE DOSENT EXIST')
// Folder does not yet exists!
await Filesystem.mkdir({
path: IMAGE_DIR,
directory: Directory.Data,
recursive: true
});
}
).then(_ => {
loading.dismiss();
});
})
}
//new method 2
private async readAsBase64(photo: Photo) {
if (this.platform.is('hybrid')) {
@@ -239,343 +117,61 @@ export class FileService {
}
}
//new method 3
async loadFiles(roomid) {
this.images = [];
const loading = await this.loadingCtrl.create({
message: 'Loading data...',
});
await loading.present();
Filesystem.readdir({
path: IMAGE_DIR,
async readFile(filePath) {
return await Filesystem.readFile({
path: filePath,
directory: Directory.Data,
}).then(result => {
console.log('ALL RESULTS', result.files[0])
let lastphoto = result.files[result.files.length - 1]
this.loadFileData(lastphoto,roomid);
},
async (err) => {
console.log('ERROR FILE DOSENT EXIST', err)
// Folder does not yet exists!
await Filesystem.mkdir({
path: IMAGE_DIR,
directory: Directory.Data,
recursive: true
});
}
).then(_ => {
loading.dismiss();
});
}
//new method 4
async loadFileData(fileName: string, roomid: any) {
async loadFileData(fileName: string) {
console.log('ALL PHOTOT FILE', fileName)
// for (let f of fileNames) {
const filePath = `${IMAGE_DIR}/${fileName}`;
const readFile = await Filesystem.readFile({
path: filePath,
directory: Directory.Data,
});
const readFile = await this.readFile(filePath)
this.images.push({
const image ={
name: fileName,
path: filePath,
data: `data:image/jpeg;base64,${readFile.data}`,
});
};
console.log('ALL IMAGE', this.images)
console.log('ALL IMAGE', image)
this.capturedImage = this.images[0].data
const capturedImage = image.data
this.capturedImageTitle = new Date().getTime() + '.jpeg';
const base64 = await fetch(this.capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.uploadFile(formData).toPromise()
console.log(guid.path);
const capturedImageTitle = new Date().getTime() + '.jpeg';
this.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
let body = {
"message":
{
"rid": roomid,
"msg": "",
"attachments": [{
"title": this.capturedImageTitle,
"title_link_download": false,
"image_url": fileImage,
}],
"file":{
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
}
}
}
console.log('BODY TAKE PICTURE CHAT', body)
const loader = this.toastService.loading();
this.chatService.sendMessage(body).subscribe(res=> {
console.log(res);
loader.remove();
},(error) => {
loader.remove();
this.toastService.badRequest("Não foi possível adicionar a fotografia!");
});
});
}
});
}
async addCameraPictureToChat(roomId){
console.log('add camera to picture')
const image = await Camera.getPhoto({
quality: 50,
allowEditing: false,
resultType: CameraResultType.Uri,
source: CameraSource.Camera // Camera, Photos or Prompt!
});
if (image) {
await this.saveImage(image,roomId)
} else {
console.log('Error saving image')
}
//this.capturedImage = this.capturedImage;
return { capturedImage, capturedImageTitle}
}
async addPictureToChatMobile(roomId) {
const capturedImage = await Camera.getPhoto({
quality: 50,
// allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Photos
});
if (capturedImage) {
await this.saveImage(capturedImage,roomId)
}
/* const response = await fetch(capturedImage.webPath!);
const blob = await response.blob();
this.photos.unshift({
filepath: "soon...",
webviewPath: capturedImage.webPath
});
this.capturedImage = await this.convertBlobToBase64(blob);
this.capturedImageTitle = new Date().getTime() + '.jpeg';
//const loader = this.toastService.loading();
let body = {
"message":
{
"rid": roomId,
"msg": "",
"attachments": [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
"image_url": this.capturedImage,
}]
}
}
this.chatService.sendMessage(body).subscribe(res=> {
//loader.remove();
//console.log(res);
},(error) => {
//loader.remove();
});
*/ }
addPictureToChat(roomId) {
console.log('add picture to chat')
const input = this.fileLoaderService.createInput({
accept: ['image/apng', 'image/jpeg', 'image/png']
})
input.onchange = async () => {
//alert('Onchange AQUI')
const file = this.fileLoaderService.getFirstFile(input)
console.log('first file',file);
const formData = new FormData();
formData.append("blobFile", file);
let guid: any = await this.uploadFile(formData).toPromise()
console.log('ADD IMAGE FORM DATA', formData)
console.log('add picture to chat', guid.path);
this.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
let body = {
"message":
{
"rid": roomId,
"msg": "",
"attachments": [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}],
"file": {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
}
}
}
console.log('SELECT PICTURE GALLERY', body)
console.log(this.capturedImage)
this.chatService.sendMessage(body).subscribe(res => {
console.log('Msg after send image', res);
}, (error) => {
console.log('Msg after send image error', error);
});
});
}
});
/* const imageData = await this.fileToBase64Service.convert(file)
this.capturedImage = imageData; */
//console.log(this.capturedImage)
};
}
addDocumentToChat(roomId:string) {
getFileFromDevice(types: typeof FileType[]) {
const input = this.fileLoaderService.createInput({
accept: ['.doc', '.docx', '.pdf']
accept: types
})
input.onchange = async () => {
const loader = this.toastService.loading();
const file = this.fileLoaderService.getFirstFile(input)
return new Promise((resolve, reject)=>{
input.onchange = async () => {
const file = this.fileLoaderService.getFirstFile(input)
resolve(file);
};
})
console.log(file);
const formData = new FormData();
formData.append('file', file, file.name);
this.chatService.uploadFile(formData, roomId).subscribe(res=> {
console.log(res);
loader.remove();
},(error) => {
loader.remove();
});
//console.log(this.capturedImage)
};
}
async addDocGestaoDocumentalToChat(roomId:string){
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){
const loader = this.toastService.loading();
this.documents.push(data.selected);
console.log(res.data.selected);
console.log(res.data.selected.Id);
console.log(res.data.selected.ApplicationType);
let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
console.log(url_no_options);
let body = {
"message":
{
"rid": roomId,
"msg": "",
"alias": "documento",
"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"
}],
"file":{
"name": res.data.selected.Assunto,
"type": "application/webtrix",
"ApplicationId": res.data.selected.ApplicationType,
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
}
}
}
this.chatService.sendMessage(body).subscribe(res=> {
loader.remove();
console.log(res);
},(error) => {
loader.remove();
});
loader.remove();
}
});
}
viewDocumentByUrl(url) {
const browser = this.iab.create(url,"_parent");
browser.show();
}
}