Files
doneit-web/src/app/services/functions/file.service.ts
T
ivan gomes dc84401716 save
2021-12-03 17:27:10 +01:00

460 lines
12 KiB
TypeScript

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 {
FileSharer} from '@byteowls/capacitor-filesharer';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Share } from '@capacitor/share';
import { HttpClient } from '@angular/common/http';
const IMAGE_DIR = 'stored-images';
interface LocalFile {
name: string;
path: string;
data: string;
}
@Injectable({
providedIn: 'root'
})
export class FileService {
images: LocalFile[] = [];
capturedImage:any;
capturedImageTitle:any;
documents:SearchList[] = [];
showLoader: boolean;
files: Set<File>;
photos: any[] = [];
idroom: any;
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
) { }
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;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
loadPicture() {
const input = this.fileLoaderService.createInput({
accept: ['image/apng', 'image/jpeg', 'image/png']
})
input.onchange = async () => {
const file = this.fileLoaderService.getFirstFile(input)
console.log(file);
const imageData = await this.fileToBase64Service.convert(file)
this.capturedImage = imageData;
this.capturedImageTitle = file.name;
let data = {
image:this.capturedImage,
name: this.capturedImageTitle
}
return data;
};
}
//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
this.capturedImageTitle = new Date().getTime() + '.jpeg';
let body = {
"message":
{
"rid": roomid,
"msg": "",
"attachments": [{
"title": this.capturedImageTitle,
"title_link_download": false,
"image_url": this.capturedImage,
}]
}
}
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){
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)
}
await Share.share({
title: 'Check my image',
url: image.path
})
}
async addPictureToChatMobile(roomId) {
const capturedImage = await Camera.getPhoto({
quality: 50,
// allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Camera
});
if (capturedImage) {
await this.saveImage(capturedImage,roomId)
}
await Share.share({
title: 'Check my image',
url: capturedImage.path
})
/* 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();
});
*/ }
async shareLocalFile(){
this.http.get('./assets/any.svg', {responseType: 'blob'}).subscribe(res=>{
const reader = new FileReader()
reader.onloadend=()=>{
const result = reader.result as string
const base64Data = result.split(',')[1]
FileSharer.share({
filename:'any.pdf',
base64Data,
contentType: "application/pdf",
})
reader.readAsDataURL(res)
}
})
}
addPictureToChat(roomId) {
const input = this.fileLoaderService.createInput({
accept: ['image/apng', 'image/jpeg', 'image/png']
})
setInterval(()=>{
console.log(input.value)
}, 550)
input.onchange = async () => {
//alert('Onchange AQUI')
const file = this.fileLoaderService.getFirstFile(input)
console.log(file);
const loader = this.toastService.loading();
const imageData = await this.fileToBase64Service.convert(file)
this.capturedImage = imageData;
this.capturedImageTitle = file.name;
let body = {
"message":
{
"rid": roomId,
"msg": "",
"attachments": [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
"image_url": this.capturedImage,
}]
}
}
console.log('SELECT PICTURE GALLERY', body)
console.log(this.capturedImage)
this.chatService.sendMessage(body).subscribe(res=> {
loader.remove();
//console.log(res);
},(error) => {
loader.remove();
});
//console.log(this.capturedImage)
};
}
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);
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": "",
"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();
}
}