Files
doneit-web/src/app/services/functions/file.service.ts
T

582 lines
17 KiB
TypeScript
Raw Normal View History

2021-09-13 12:37:58 +01:00
import { Injectable } from '@angular/core';
import { FileLoaderService } from '../file/file-loader.service';
import { FileToBase64Service } from '../file/file-to-base64.service';
2021-09-14 15:57:24 +01:00
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
2021-11-09 15:28:40 +01:00
2021-09-21 14:05:59 +01:00
import { ChatService } from '../chat.service';
2021-11-21 19:49:59 +01:00
import { ModalController, Platform,LoadingController } from '@ionic/angular';
2021-09-21 14:05:59 +01:00
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';
2021-11-09 15:28:40 +01:00
import { Camera, CameraResultType, CameraSource, Photo} from '@capacitor/camera';
2021-11-21 19:49:59 +01:00
import { Filesystem, Directory } from '@capacitor/filesystem';
2021-12-06 16:00:57 +01:00
import { environment } from 'src/environments/environment';
2021-12-16 16:36:39 +01:00
import { HttpClient, HttpEventType, HttpHeaders, HttpParams } from '@angular/common/http';
2022-01-25 14:36:31 +01:00
import { Storage } from '@ionic/storage';
2021-11-21 19:49:59 +01:00
const IMAGE_DIR = 'stored-images';
2021-12-03 17:27:10 +01:00
2021-11-21 19:49:59 +01:00
interface LocalFile {
name: string;
path: string;
data: string;
}
2021-09-13 12:37:58 +01:00
@Injectable({
providedIn: 'root'
})
export class FileService {
2021-11-21 19:49:59 +01:00
images: LocalFile[] = [];
2021-09-13 12:37:58 +01:00
capturedImage:any;
capturedImageTitle:any;
2021-09-21 14:05:59 +01:00
documents:SearchList[] = [];
showLoader: boolean;
2021-09-13 12:37:58 +01:00
files: Set<File>;
2021-11-09 15:28:40 +01:00
photos: any[] = [];
2021-11-21 19:49:59 +01:00
idroom: any;
2021-12-06 16:00:57 +01:00
headers: HttpHeaders;
2021-12-16 16:36:39 +01:00
downloadProgess = 0;
downloadFilename: any;
2022-02-03 16:36:05 +01:00
convertBlobToBase64Worker;
2021-12-06 16:00:57 +01:00
2021-09-13 12:37:58 +01:00
constructor(
private fileLoaderService: FileLoaderService,
private fileToBase64Service: FileToBase64Service,
2021-09-14 15:57:24 +01:00
private iab: InAppBrowser,
2021-09-21 14:05:59 +01:00
private chatService: ChatService,
private modalController: ModalController,
private processesService: ProcessesService,
private toastService: ToastService,
2021-11-21 19:49:59 +01:00
private platform: Platform,
2021-12-06 16:00:57 +01:00
private loadingCtrl: LoadingController,
private http: HttpClient,
2022-01-25 14:36:31 +01:00
private storage: Storage
2021-12-14 14:58:34 +01:00
) {
this.headers = new HttpHeaders();
}
2021-09-13 12:37:58 +01:00
2021-12-06 16:00:57 +01:00
uploadFile(formData:any){
2022-01-07 16:01:17 +01:00
console.log('UPLOAD file', formData)
2021-12-06 16:00:57 +01:00
//const geturl = environment.apiURL + 'Tasks/DelegateTask';
2021-12-16 16:36:39 +01:00
const geturl = environment.apiURL + 'ObjectServer/UploadFiles';
2021-12-06 16:00:57 +01:00
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);
2021-12-14 14:58:34 +01:00
this.headers = this.headers.set('responseType', 'blob');
this.headers = this.headers.set('Content-Type', 'application/octet-stream');
2021-12-06 16:00:57 +01:00
let options = {
headers: this.headers,
params: params
};
return this.http.get<any>(`${geturl}`, options);
}
2021-12-16 16:36:39 +01:00
downloadFile(guid:any) {
2021-12-17 17:20:43 +01:00
let downloadUrl = environment.apiURL +'objectserver/streamfiles?path='+guid;
2021-12-16 16:36:39 +01:00
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 );
}
2021-11-09 15:28:40 +01:00
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();
2021-09-14 10:30:13 +01:00
2021-11-09 15:28:40 +01:00
this.photos.unshift({
filepath: "soon...",
webviewPath: capturedImage.webPath
});
2021-09-14 10:30:13 +01:00
2021-11-09 15:28:40 +01:00
this.capturedImage = await this.convertBlobToBase64(blob);
2021-09-14 10:30:13 +01:00
this.capturedImageTitle = new Date().getTime() + '.jpeg';
2021-11-09 15:28:40 +01:00
2021-09-14 10:30:13 +01:00
let data = {
image:this.capturedImage,
name: this.capturedImageTitle
}
return data;
}
2021-11-09 15:28:40 +01:00
convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
2022-02-03 16:36:05 +01:00
async loadPicture(roomid) {
const capturedImage = await Camera.getPhoto({
quality: 90,
// allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Photos
});
2021-09-13 12:37:58 +01:00
2022-02-03 16:36:05 +01:00
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);
2021-09-13 12:37:58 +01:00
2022-02-03 16:36:05 +01:00
this.downloadFile(guid.path).subscribe(async (event) => {
2021-09-13 12:37:58 +01:00
2022-02-03 16:36:05 +01:00
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!");
});
2021-09-13 12:37:58 +01:00
2022-02-03 16:36:05 +01:00
});
}
});
2021-09-13 12:37:58 +01:00
}
2021-09-14 15:57:24 +01:00
2021-11-21 19:49:59 +01:00
//new method1
async saveImage(photo: Photo, roomid: any) {
const base64Data = await this.readAsBase64(photo);
const fileName = new Date().getTime() + '.jpeg';
const savedFile = await Filesystem.writeFile({
path: `${IMAGE_DIR}/${fileName}`,
data: base64Data,
directory: Directory.Data
});
this.loadFiles(roomid);
}
//new method 2
private async readAsBase64(photo: Photo) {
if (this.platform.is('hybrid')) {
const file = await Filesystem.readFile({
path: photo.path
});
return file.data;
}
else {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(photo.webPath);
const blob = await response.blob();
return await this.convertBlobToBase64(blob) as string;
}
}
//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,
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) {
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,
});
this.images.push({
name: fileName,
path: filePath,
data: `data:image/jpeg;base64,${readFile.data}`,
});
console.log('ALL IMAGE', this.images)
this.capturedImage = this.images[0].data
2021-12-06 16:00:57 +01:00
2021-11-21 19:49:59 +01:00
this.capturedImageTitle = new Date().getTime() + '.jpeg';
2022-01-27 15:53:20 +01:00
const base64 = await fetch(this.capturedImage);
const blob = await base64.blob();
2022-01-05 21:27:26 +01:00
const formData = new FormData();
2022-01-27 15:53:20 +01:00
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.uploadFile(formData).toPromise()
2022-01-05 21:27:26 +01:00
console.log(guid.path);
2021-11-21 19:49:59 +01:00
2022-01-27 15:53:20 +01:00
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!");
});
2022-02-02 10:10:57 +01:00
2022-01-27 15:53:20 +01:00
});
2022-01-05 21:27:26 +01:00
}
2022-02-02 10:10:57 +01:00
2022-01-27 15:53:20 +01:00
});
2021-11-21 19:49:59 +01:00
}
2021-11-09 15:28:40 +01:00
async addCameraPictureToChat(roomId){
2021-10-08 15:37:24 +01:00
2022-01-27 15:53:20 +01:00
console.log('add camera to picture')
2021-11-21 19:49:59 +01:00
const image = await Camera.getPhoto({
quality: 50,
allowEditing: false,
2021-11-09 15:28:40 +01:00
resultType: CameraResultType.Uri,
2021-11-21 19:49:59 +01:00
source: CameraSource.Camera // Camera, Photos or Prompt!
2021-11-09 15:28:40 +01:00
});
2021-11-21 19:49:59 +01:00
if (image) {
await this.saveImage(image,roomId)
2022-01-27 15:53:20 +01:00
} else {
console.log('Error saving image')
2021-11-21 19:49:59 +01:00
}
2021-10-08 15:37:24 +01:00
2021-11-21 19:49:59 +01:00
//this.capturedImage = this.capturedImage;
2021-12-06 16:00:57 +01:00
2021-10-08 15:37:24 +01:00
}
2021-11-09 15:28:40 +01:00
async addPictureToChatMobile(roomId) {
2021-10-08 15:37:24 +01:00
2021-11-09 15:28:40 +01:00
const capturedImage = await Camera.getPhoto({
2021-11-21 19:49:59 +01:00
quality: 50,
2021-11-09 15:28:40 +01:00
// allowEditing: true,
resultType: CameraResultType.Uri,
2022-02-03 16:36:05 +01:00
source: CameraSource.Photos
2021-10-08 15:37:24 +01:00
2021-11-09 15:28:40 +01:00
});
2021-11-21 19:49:59 +01:00
if (capturedImage) {
await this.saveImage(capturedImage,roomId)
}
2021-12-03 17:27:10 +01:00
2021-11-21 19:49:59 +01:00
/* const response = await fetch(capturedImage.webPath!);
2021-11-09 15:28:40 +01:00
const blob = await response.blob();
this.photos.unshift({
filepath: "soon...",
webviewPath: capturedImage.webPath
});
this.capturedImage = await this.convertBlobToBase64(blob);
2021-10-08 15:37:24 +01:00
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();
});
2021-11-21 19:49:59 +01:00
*/ }
2022-01-25 14:36:31 +01:00
addPictureToChat(roomId) {
2021-09-21 14:05:59 +01:00
2022-01-25 14:36:31 +01:00
console.log('add picture to chat')
2021-10-08 15:37:24 +01:00
2022-01-25 14:36:31 +01:00
const input = this.fileLoaderService.createInput({
accept: ['image/apng', 'image/jpeg', 'image/png']
})
2022-01-07 16:01:17 +01:00
2022-01-25 14:36:31 +01:00
input.onchange = async () => {
2021-10-08 15:37:24 +01:00
2022-01-25 14:36:31 +01:00
//alert('Onchange AQUI')
2021-09-21 14:05:59 +01:00
2022-01-25 14:36:31 +01:00
const file = this.fileLoaderService.getFirstFile(input)
2021-10-08 15:37:24 +01:00
2022-01-27 15:53:20 +01:00
console.log('first file',file);
2021-09-21 14:05:59 +01:00
2022-01-25 14:36:31 +01:00
const formData = new FormData();
formData.append("blobFile", file);
let guid: any = await this.uploadFile(formData).toPromise()
2022-01-27 15:53:20 +01:00
console.log('ADD IMAGE FORM DATA', formData)
2022-01-25 14:36:31 +01:00
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);
2022-01-27 15:53:20 +01:00
await this.storage.set(guid.path, fileImage).then(() => {
2022-01-25 14:36:31 +01:00
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
}
}
}
2021-12-06 16:00:57 +01:00
2022-01-25 14:36:31 +01:00
console.log('SELECT PICTURE GALLERY', body)
console.log(this.capturedImage)
2021-12-06 16:00:57 +01:00
2022-01-25 14:36:31 +01:00
this.chatService.sendMessage(body).subscribe(res => {
2021-09-21 14:05:59 +01:00
2022-01-25 14:36:31 +01:00
console.log('Msg after send image', res);
}, (error) => {
console.log('Msg after send image error', error);
});
});
2021-09-21 14:05:59 +01:00
}
2022-01-25 14:36:31 +01:00
});
2021-10-07 15:30:36 +01:00
2022-01-25 14:36:31 +01:00
/* const imageData = await this.fileToBase64Service.convert(file)
this.capturedImage = imageData; */
2021-12-06 16:00:57 +01:00
2022-01-25 14:36:31 +01:00
//console.log(this.capturedImage)
};
}
2021-09-21 14:05:59 +01:00
addDocumentToChat(roomId:string) {
const input = this.fileLoaderService.createInput({
accept: ['.doc', '.docx', '.pdf']
})
input.onchange = async () => {
const loader = this.toastService.loading();
const file = this.fileLoaderService.getFirstFile(input)
console.log(file);
const formData = new FormData();
formData.append('file', file, file.name);
2021-09-21 14:05:59 +01:00
this.chatService.uploadFile(formData, roomId).subscribe(res=> {
console.log(res);
2021-09-21 14:05:59 +01:00
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=>{
2021-09-23 12:13:20 +01:00
const data = res.data;
if(data.selected){
2021-09-21 14:05:59 +01:00
const loader = this.toastService.loading();
2021-09-23 12:13:20 +01:00
2021-09-21 14:05:59 +01:00
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",
2021-09-21 14:05:59 +01:00
"attachments": [{
"title": res.data.selected.Assunto,
2021-09-23 12:13:20 +01:00
"description": res.data.selected.DocTypeDesc,
2021-09-21 14:05:59 +01:00
"title_link": url_no_options,
"title_link_download": true,
2021-09-23 12:13:20 +01:00
//"thumb_url": "assets/images/webtrix-logo.png",
2021-09-21 14:05:59 +01:00
"message_link": url_no_options,
"type": "webtrix"
2021-09-23 12:13:20 +01:00
}],
"file":{
"name": res.data.selected.Assunto,
2021-10-09 16:41:18 +01:00
"type": "application/webtrix",
"ApplicationId": res.data.selected.ApplicationType,
"DocId": res.data.selected.Id,
2021-10-09 20:24:34 +01:00
"Assunto": res.data.selected.Assunto,
2021-09-23 12:13:20 +01:00
}
2021-09-21 14:05:59 +01:00
}
}
this.chatService.sendMessage(body).subscribe(res=> {
loader.remove();
console.log(res);
},(error) => {
loader.remove();
});
2021-09-23 12:13:20 +01:00
loader.remove();
2021-09-21 14:05:59 +01:00
}
});
}
2021-09-14 15:57:24 +01:00
viewDocumentByUrl(url) {
2021-10-18 17:10:33 +01:00
const browser = this.iab.create(url,"_parent");
2021-09-14 15:57:24 +01:00
browser.show();
}
2021-09-13 12:37:58 +01:00
}