"mychangeTo"

This commit is contained in:
ivan gomes
2021-11-16 15:24:38 +01:00
parent 4afb3304e0
commit 24c07e3dea
3041 changed files with 1579372 additions and 80 deletions
@@ -1,5 +1,5 @@
import { Component, OnInit } from '@angular/core';
import { ModalController, NavParams } from '@ionic/angular';
import { LoadingController, ModalController, NavParams, Platform, ToastController } from '@ionic/angular';
/* import {Plugins, CameraResultType, CameraSource} from '@capacitor/core'; */
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
@@ -9,14 +9,26 @@ import { Image } from 'src/app/models/image';
import { PhotoService } from 'src/app/services/photo.service';
//Capacitor
//Cordova
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { ToastService } from 'src/app/services/toast.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ThemePalette } from '@angular/material/core';
import { formatDate } from 'src/plugin/momentG.js'
import { FileLoaderService } from 'src/app/services/file/file-loader.service';
import { FileToBase64Service } from 'src/app/services/file/file-to-base64.service';
import { ThemeService } from 'src/app/services/theme.service';
import { Camera, CameraResultType, CameraSource, Photo} from '@capacitor/camera';
import { Photos } from './Photos';
import { Directory, Filesystem } from '@capacitor/filesystem';
import { Capacitor } from '@capacitor/core';
import { Storage } from '@capacitor/storage'
const IMAGE_DIR = 'stored-images';
interface LocalFile {
name: string;
path: string;
data: string;
}
@Component({
selector: 'app-new-publication',
@@ -24,6 +36,7 @@ import { FileToBase64Service } from 'src/app/services/file/file-to-base64.servic
styleUrls: ['./new-publication.page.scss'],
})
export class NewPublicationPage implements OnInit {
images: LocalFile[] = [];
// date picker
public date: any;
@@ -58,92 +71,310 @@ export class NewPublicationPage implements OnInit {
guestPicture:any;
capturedImage:any;
capturedImage:any = '';
capturedImageTitle:any;
public photos: Photos[] = [];
private PHOTO_STORAGE: string = "photos";
private platform: Platform;
constructor(
private modalController: ModalController,
public photoService: PhotoService,
private navParams: NavParams,
private publications: PublicationsService,
private camera: Camera,
private toastService: ToastService,
private fileLoaderService: FileLoaderService,
private fileToBase64Service: FileToBase64Service
private fileToBase64Service: FileToBase64Service,
public ThemeService: ThemeService,
platform: Platform,
private loadingCtrl: LoadingController,
private toastCtrl: ToastController
) {
this.publicationType = this.navParams.get('publicationType');
this.folderId = this.navParams.get('folderId');
this.publicationTitle = 'Nova Publicação';
}
this.platform = platform;
}
ngOnInit() {
this.setTitle();
this.clear();
this.loadFiles()
// this.takePicture();
}
takePicture() {
const options: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
targetWidth: 720,
targetHeight: 720,
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL): m
//let base64Image = 'data:image/jpeg;base64,' + imageData;
this.capturedImage = 'data:image/png;base64,'+imageData;
this.capturedImageTitle = new Date().getTime() + '.jpeg';
}, (err) => {
/* console.log(err); */
async loadFiles() {
this.images = [];
const loading = await this.loadingCtrl.create({
message: 'Loading data...',
});
await loading.present();
Filesystem.readdir({
path: IMAGE_DIR,
directory: Directory.Data,
}).then(result => {
this.loadFileData(result.files);
},
async (err) => {
// Folder does not yet exists!
await Filesystem.mkdir({
path: IMAGE_DIR,
directory: Directory.Data,
});
}
).then(_ => {
loading.dismiss();
});
}
// Get the actual base64 data of an image
// base on the name of the file
async loadFileData(fileNames: string[]) {
for (let f of fileNames) {
const filePath = `${IMAGE_DIR}/${f}`;
const readFile = await Filesystem.readFile({
path: filePath,
directory: Directory.Data,
});
this.images.push({
name: f,
path: filePath,
data: `data:image/jpeg;base64,${readFile.data}`,
});
this.images.forEach(function(value){
this.capturedImage = value.data
})
}
}
// Little helper
async presentToast(text) {
const toast = await this.toastCtrl.create({
message: text,
duration: 3000,
});
toast.present();
}
async selectImage() {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: false,
resultType: CameraResultType.Uri,
source: CameraSource.Camera // Camera, Photos or Prompt!
});
if (image) {
this.saveImage(image)
}
}
// Create a new file from a capture image
async saveImage(photo: Photo) {
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
});
// Reload the file list
// Improve by only loading for the new image and unshifting array!
this.loadFiles();
}
// https://ionicframework.com/docs/angular/your-first-app/3-saving-photos
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;
}
}
// Helper function
convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
async startUpload(file: LocalFile) {
// TODO
}
async deleteImage(file: LocalFile) {
// TODO
}
laodPicture() {
const input = this.fileLoaderService.createInput({
accept: ['image/apng', 'image/jpeg', 'image/png']
})
input.onchange = async () => {
const file = this.fileLoaderService.getFirstFile(input)
const imageData = await this.fileToBase64Service.convert(file)
this.capturedImage = imageData;
this.capturedImageTitle = file.name
async takePicture() {
const capturedImage = await Camera.getPhoto({
quality: 90,
// allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Camera
console.log(this.capturedImage)
});
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);
console.log(this.capturedImage)
}
// helper function
// convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
// const reader = new FileReader;
// reader.onerror = reject;
// reader.onload = () => {
// resolve(reader.result);
// };
// reader.readAsDataURL(blob);
// });
// // native devices ionic capacitor
// private async readAsBase64(photo: Photo) {
// // "hybrid" will detect Cordova or Capacitor
// if (this.platform.is('hybrid')) {
// // Read the file into base64 format
// 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;
// }
// }
// Save picture to file on device
private async savePicture(photo: Photo) {
// Convert photo to base64 format, required by Filesystem API to save
const base64Data = await this.readAsBase64(photo);
// Write the file to the data directory
const fileName = new Date().getTime() + '.jpeg';
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data
});
if (this.platform.is('hybrid')) {
// Display the new image by rewriting the 'file://' path to HTTP
// Details: https://ionicframework.com/docs/building/webview#file-protocol
return {
filepath: savedFile.uri,
webviewPath: Capacitor.convertFileSrc(savedFile.uri),
};
}
else {
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: photo.webPath
getPicture() {
const options: CameraOptions = {
quality: 90,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
targetWidth: 720,
targetHeight: 720,
};
}
}
public async loadSaved() {
// Retrieve cached photo array data
const photoList = await Storage.get({ key: this.PHOTO_STORAGE });
this.photos = JSON.parse(photoList.value) || [];
// Easiest way to detect when running on the web:
// “when the platform is NOT hybrid, do this”
if (!this.platform.is('hybrid')) {
// Display the photo by reading into base64 format
for (let photo of this.photos) {
// Read each saved photo's data from the Filesystem
const readFile = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data
});
// Web platform only: Load the photo as base64 data
photo.webviewPath = `data:image/jpeg;base64,${readFile.data}`;
this.capturedImage = photo.webviewPath
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
let base64Image = 'data:image/jpeg;base64,' + imageData;
this.capturedImage = imageData;
this.capturedImageTitle = new Date().getTime() + '.jpeg';
}, (err) => {
/* console.log(err); */
});
}
}
// laodPicture() {
// const input = this.fileLoaderService.createInput({
// accept: ['image/apng', 'image/jpeg', 'image/png']
// })
// input.onchange = async () => {
// const file = this.fileLoaderService.getFirstFile(input)
// const imageData = await this.fileToBase64Service.convert(file)
// this.capturedImage = imageData;
// this.capturedImageTitle = file.name
// console.log(this.capturedImage)
// };
// }
runValidation() {
this.validateFrom = true
@@ -166,19 +397,17 @@ export class NewPublicationPage implements OnInit {
])
})
}
async save() {
this.injectValidation()
this.runValidation()
if(this.Form.invalid) return false
if(this.publicationType == '3') {
console.log(this.navParams.get('publication'));
if(this.capturedImage != '') {
this.publication = {
DateIndex: this.publication.DateIndex,
@@ -196,7 +425,7 @@ export class NewPublicationPage implements OnInit {
try {
console.log(this.publication);
await this.publications.UpdatePublication(this.publication.ProcessId, this.publication).toPromise()
this.toastService.successMessage("Publicação criado")
@@ -230,7 +459,7 @@ export class NewPublicationPage implements OnInit {
console.log(this.publication);
await this.publications.UpdatePublication(this.publication.ProcessId, this.publication).toPromise()
this.toastService.successMessage("Publicação criado")
this.close();
} catch (error) {
this.toastService.badRequest("Publicação não criado")
@@ -292,7 +521,7 @@ export class NewPublicationPage implements OnInit {
await this.publications.CreatePublication(this.folderId, this.publication).toPromise();
this.close();
this.toastService.successMessage("Publicação criado")
this.close();
} catch (error) {
@@ -304,13 +533,14 @@ export class NewPublicationPage implements OnInit {
}
}
close() {
this.modalController.dismiss().then(()=>{
this.showLoader=true;
});
}
clear() {
this.capturedImage = '';
}
@@ -350,8 +580,8 @@ export class NewPublicationPage implements OnInit {
source: CameraSource.Camera
});
console.log(image);
this.photo = this.sanitizer.bypassSecurityTrustResourceUrl(image && (image.dataUrl));
} */
}
}