Files
doneit-web/src/app/shared/publication/new-publication/new-publication.page.ts
T
Peter Maquiran cbb7657b90 merge
2024-01-29 17:25:05 +01:00

1491 lines
49 KiB
TypeScript

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { PublicationsService } from 'src/app/services/publications.service';
import { Publication } from 'src/app/models/publication';
import { PhotoService } from 'src/app/services/photo.service';
import { ToastService } from 'src/app/services/toast.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ThemeService } from 'src/app/services/theme.service';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { HttpErrorHandle } from 'src/app/services/http-error-handle.service';
import { PublicationFolderService } from 'src/app/store/publication-folder.service';
import { FilePicker } from '@capawesome/capacitor-file-picker';
import { checkFileTypeService } from 'src/app/services/checkFileType.service';
import { FileValidatorService } from "src/app/services/file/file-validator.service";
import { MiddlewareServiceService } from "src/app/shared/API/middleware/middleware-service.service";
import { LakefsRepositoryService } from '../../repository/lakefs/lakefs-repository.service';
import { ok, err, Result } from 'neverthrow';
import { ObjectMergeNotification, SocketConnectionMCRService } from "src/app/services/socket-connection-mcr.service"
import { CMAPIService } from '../../repository/CMAPI/cmapi.service';
import { environment } from 'src/environments/environment';
import { CaptureError, CaptureImageOptions, MediaCapture, MediaFile } from '@awesome-cordova-plugins/media-capture/ngx';
import { Filesystem, Directory, Encoding, FilesystemDirectory } from '@capacitor/filesystem';
import { Platform } from '@ionic/angular';
import { Capacitor } from '@capacitor/core';
enum ActionType {
newRapid = "1",
new = "2",
edit = "3"
}
@Component({
selector: 'app-new-publication',
templateUrl: './new-publication.page.html',
styleUrls: ['./new-publication.page.scss'],
})
export class NewPublicationPage implements OnInit {
showLoader: boolean;
pub: Publication = new Publication();
publicationTitle: string;
imgUrl: any;
Defaultimage: any = '';
Form: FormGroup;
validateFrom = false
@Input() publication!: Publication;
@Input() publicationType: string;
@Input() folderId: string;
@Input() documentId: string;
@Output() closeDesktopComponent = new EventEmitter<any>();
@Output() openPublicationDetails = new EventEmitter<any>();
@Output() goBackToViewPublications = new EventEmitter<any>();
@Output() goBacktoPublicationDetails = new EventEmitter<any>();
guestPicture: any;
capturedImage: any = '';
capturedImageTitle: any = '';
fileType: string;
filecontent: boolean;
captureContent: any;
seletedContent: PublicationAttachmentEntity[] = []
displayLimit = 4;
filesSizeSum = 0;
photoOrVideo: boolean = false;
video: any;
publicationFormMV = new PublicationFormMV()
constructor(
public photoService: PhotoService,
private publications: PublicationsService,
private toastService: ToastService,
public ThemeService: ThemeService,
private httpErroHandle: HttpErrorHandle,
public PublicationFolderService: PublicationFolderService,
public checkFileType: checkFileTypeService,
private FileValidatorService: FileValidatorService,
private MiddlewareServiceService: MiddlewareServiceService,
private LakefsRepositoryService: LakefsRepositoryService,
private SocketConnectionMCRService: SocketConnectionMCRService,
private CMAPIService: CMAPIService,
private mediaCapture: MediaCapture,
private httpErrorHandle: HttpErrorHandle,
private platform: Platform,
) {
this.publicationTitle = 'Nova Publicação';
if (this.publication) {
this.seletedContent = this.publication.Files;
this.filecontent = true;
}
this.SocketConnectionMCRService.connect()
}
ngOnInit() {
this.publication = {
DateIndex: "",
DocumentId: 0,
ProcessId: "",
Title: "",
Message: "",
DatePublication: "",
Files: [],
OriginalFileName: "",
}
this.pub = this.publication;
this.setTitle();
this.setData()
}
setData() {
if (!this.publicationType) {
setTimeout(() => {
this.setData()
}, 500)
} else {
// this.pub = this.publication
// this.publication = null
this.getPublicationDetail()
}
}
getPublicationDetail() {
console.log('edit 1', this.publicationType)
if (this.publicationType != ActionType.new) {
this.showLoader = true;
this.publications.GetPublicationWithArrayOfFilesById(this.documentId).subscribe(res => {
this.publication = {
DateIndex: res.DateIndex,
DocumentId: res.DocumentId,
ProcessId: res.ProcessId,
Title: res.Title,
Message: res.Message,
DatePublication: res.DatePublication,
Files: res.Files,
OriginalFileName: res.OriginalFileName,
FileExtension: res.FileExtension,
}
console.log('edit', this.publication)
this.pub = this.publication;
this.seletedContent = this.publication.Files.map(e => {
return new PublicationAttachmentEntity(
{
base64: e.FileBase64,
extension: e.FileExtension,
OriginalFileName: e.OriginalFileName,
FileType: this.checkFileType.checkFileType(e.FileExtension)
}
)
})
this.showLoader = false;
}, (error) => {
console.log(error)
this.showLoader = false;
this.goBack()
});
}
}
async takePicture() {
const capturedImage = await Camera.getPhoto({
quality: 50,
// allowEditing: true,
resultType: CameraResultType.Base64,
source: CameraSource.Camera
});
this.capturedImage = 'data:image/jpeg;base64,' + capturedImage.base64String;
this.capturedImageTitle = 'foto';
/* if(validation.isOk) { */
const compressedImage = await this.compressImageBase64(
this.capturedImage,
800, // maxWidth
800, // maxHeight
0.9 // quality
).then((picture) => {
this.photoOrVideo = false;
let fileObject = {
FileBase64: picture,
FileExtension: this.removeTextBeforeSlash('jpeg', '/'),
OriginalFileName: 'imagem'
}
const FileExtension = this.removeTextBeforeSlash('jpeg', '/')
const newAttachment = new PublicationAttachmentEntity(
{
base64: picture,
extension: FileExtension,
OriginalFileName: "foto",
FileType: 'image'
}
)
newAttachment.needUpload()
this.seletedContent.push(newAttachment)
});
/* } else {
this.toastService._badRequest("Imagem inválida")
} */
}
async laodPicture() {
const capturedImage = await Camera.getPhoto({
quality: 90,
resultType: CameraResultType.Base64,
source: CameraSource.Photos
});
this.fileType = capturedImage.format
console.log(this.fileType)
this.capturedImage = 'data:image/jpeg;base64,' + capturedImage.base64String;
this.capturedImageTitle = 'foto';
const compressedImage = await this.compressImageBase64(
this.capturedImage,
800, // maxWidth
800, // maxHeight
0.9 // quality
).then((picture) => {
let fileObject = {
FileBase64: picture,
FileExtension: this.removeTextBeforeSlash('jpeg', '/'),
OriginalFileName: 'image'
}
const FileExtension = this.removeTextBeforeSlash('jpeg', '/')
const newAttachment = new PublicationAttachmentEntity(
{
base64: picture,
extension: FileExtension,
OriginalFileName: "foto",
FileType: 'image'
}
)
newAttachment.needUpload();
this.seletedContent.push(newAttachment)
});
}
async loadVideo() {
const result = await FilePicker.pickMedia
({
multiple: true,
});
console.log(result)
result.files.forEach(async blobFile => {
console.log(blobFile)
if (this.checkFileType.checkFileType(blobFile.mimeType) == 'image' || this.checkFileType.checkFileType(blobFile.mimeType) == 'video') {
/* console.log('converte new way',this.getBase64(blobFile)) */
/* const blob = await fetch(
Capacitor.convertFileSrc(blobFile.path)
).then(r => r.blob()); */
/* console.log(await blob.arrayBuffer());
console.log("base64 :data:video/mp4;base64,",this.arrayBufferToBase64(await blob.arrayBuffer())) */
this.convertBlobToBase64(blobFile.blob).then((value) => {
console.log(value)
this.filesSizeSum = this.filesSizeSum + blobFile.size
if (this.fileSizeToMB(this.filesSizeSum) <= 20) {
const FileExtension = this.removeTextBeforeSlash(blobFile.mimeType, '/')
const file = new File([blobFile.blob], blobFile.name);
const newAttachment = new PublicationAttachmentEntity(
{
base64: value,
extension: FileExtension,
blobFile: file,
FileType: this.checkFileType.checkFileType(FileExtension)
}
)
newAttachment.needUpload()
this.seletedContent.push(newAttachment)
console.log(this.seletedContent)
this.filecontent = true;
} else {
if (this.seletedContent.length === 0)
this.filesSizeSum = 0
this.httpErroHandle.validationMessagge('filessize');
}
}).catch((erro) => {
console.log(erro)
})
} else {
this.httpErroHandle.validationMessagge('filetype');
}
});
/* this.capturedImage = 'data:image/jpeg;base64,' +capturedImage.base64String;
this.capturedImageTitle = 'foto';
const validation = await this.FileValidatorService.ValidateImage(this.capturedImage)
if(validation.isOk) {
const compressedImage = await this.compressImageBase64(
this.capturedImage,
800, // maxWidth
800, // maxHeight
0.9 // quality
).then((picture) => {
console.log('Selected: ', picture)
this.capturedImage = picture
});
} else {
this.toastService._badRequest("Imagem inválida")
} */
};
async loadVideoTablet() {
const result = await FilePicker.pickMedia
({
multiple: true,
});
console.log(result.files)
result.files.forEach(element => {
this.filesSizeSum = this.filesSizeSum + element.size
if (this.fileSizeToMB(this.filesSizeSum) <= 20) {
if (this.checkFileType.checkFileType(element.mimeType) == 'image' || this.checkFileType.checkFileType(element.mimeType) == 'video') {
let resultUrl = decodeURIComponent(element.path);
try {
Filesystem.readFile({ path: resultUrl })
.then(async (content) => {
console.log(result)
console.log('load video tablet base64',content)
this.filecontent = true;
let fileObject = new PublicationAttachmentEntity ({
base64: content.data,
extension: this.removeTextBeforeSlash(element.mimeType, '/'),
OriginalFileName: 'video',
FileType: this.checkFileType.checkFileType( this.removeTextBeforeSlash(element.mimeType, '/'))
})
this.seletedContent.push(fileObject)
})
.catch((err) => console.error(err));
} catch (error) {
console.log('upload video error: ', error)
}
}
} else {
if (this.seletedContent.length === 0)
this.filesSizeSum = 0
this.httpErrorHandle.validationMessagge('filessize')
}
});
};
runValidation() {
this.validateFrom = true
}
injectValidation() {
this.Form = new FormGroup({
Subject: new FormControl(this.pub.Title, [
Validators.required,
// Validators.minLength(4)
]),
Message: new FormControl(this.pub.Message, [
Validators.required,
Validators.maxLength(1000)
])
})
}
async save() {
this.injectValidation()
this.runValidation()
if (this.Form.invalid) {
return false
} else {
}
if (this.seletedContent.length == 0) {
const newAttachment = new PublicationAttachmentEntity(
{
base64: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgMAAAIJCAIAAAC3IqlmAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAABSKSURBVHhe7d1ncuNGo4bRu/8lfh5F5qToBdyWNJbHDYgAmETqPVXnh4PAhKp+iMDu/3v9+28AkikBQDolAEinBADplAAgnRIApFMCgHRKAJBOCQDSKQFAOiUASKcEAOmUACCdEgCkUwKAdEoAkE4JANIpAUA6JQBIpwQA6ZQAIJ0SAKRTAoB0SgCQTgkA0ikBQDolAEinBADplAAgnRIApFMCgHRKAJBOCQDSKQFAOiUASKcEAOmUACCdEgCkUwKAdEoAkE4JANIpAUA6JQBIpwQA6ZQAIJ0SAKRTAoB0SgCQTgkA0ikBQDolAEinBADplAAgnRIApFMCgHRKAJBOCQDSKQFAOiUASKcEAOmUACCdEgCkUwKAdEoAkE4JANIpAUA6JQBIpwQA6ZQAIJ0SAKRTAoB0SgCQTgkA0ikB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AIJ0SAKRTAoB0SgCQTgkA0ikBQDolAEinBADplAAgnRIApFMCgHRKAJBOCQCy/f33/wPavQjXs/ARnQAAAABJRU5ErkJggg==",
extension: "png",
OriginalFileName: "foto",
FileType: 'image'
}
)
this.seletedContent.push(newAttachment)
}
if (this.publicationType == ActionType.edit) {
if (this.seletedContent.length >= 1) {
const loader = this.toastService.loading()
this.publication = {
DateIndex: this.publication.DateIndex,
DocumentId: this.publication.DocumentId,
ProcessId: this.publication.ProcessId,
Title: this.pub.Title,
Message: this.pub.Message,
DatePublication: this.publication.DatePublication,
Files: this.seletedContent,
}
this.publicationFormMV.setDataToFrom(this.publication)
const upload = await this.publicationFormMV.uploadVideosFiles()
if(upload) {
this.publication.Files = this.publication.Files.map((e:PublicationAttachmentEntity)=> {
if(e.FileType == 'video') {
e.FileBase64 = environment.apiURL + "/ObjectServer/StreamFiles?path="+ e.chucksManager.path
}
return e
})
console.log("this.publication.Files", this.publication.Files)
}
this.publication.Files = this.publication.Files.map(e => ({
FileBase64: e.FileBase64,
FileExtension: e.FileExtension,
OriginalFileName: 'foto'
}))
try {
const response = await this.publications.UpdatePublication(this.publication.ProcessId, this.publication).toPromise()
this.httpErroHandle.httpsSucessMessagge('Editar publicação')
this.goBack();
} catch (error) {
this.httpErroHandle.httpStatusHandle(error)
if (error.status == 404) {
this.PublicationFolderService.deletePost(this.publication.ProcessId, this.publication.DocumentId)
this.goBack();
}
} finally {
loader.remove()
}
} else {
this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo")
}
}
else {
let time = new Date()
if (this.seletedContent.length >= 1) {
this.publication = {
DateIndex: time,
DocumentId: null,
ProcessId: this.folderId,
Title: this.pub.Title,
Message: this.pub.Message,
DatePublication: time,
OriginalFileName: this.capturedImageTitle || 'foto',
Files: this.seletedContent,
}
this.publicationFormMV.setDataToFrom(this.publication)
const upload = await this.publicationFormMV.uploadVideosFiles()
if(upload) {
this.publication.Files = this.publication.Files.map((e:PublicationAttachmentEntity)=> {
if(e.FileType == 'video') {
e.FileBase64 = environment.apiURL + "/ObjectServer/StreamFiles?path="+ e.chucksManager.path
}
return e
})
console.log("this.publication.Files", this.publication.Files)
}
this.publication.Files = this.publication.Files.map(e => ({
FileBase64: e.FileBase64,
FileExtension: e.FileExtension,
OriginalFileName: 'foto'
}))
const loader = this.toastService.loading()
try {
await this.publications.CreatePublication(this.publication.ProcessId, this.publication).toPromise()
if (this.publicationTitle == '1') {
} else if (this.publicationTitle == '2') {
this.httpErroHandle.httpsSucessMessagge('Criar publicação')
} else if (this.publicationTitle == '3') {
this.httpErroHandle.httpsSucessMessagge('Editar publicação')
}
this.goBackToViewPublications.emit();
} catch (error) {
this.httpErroHandle.httpStatusHandle(error)
} finally {
loader.remove()
}
} else {
this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo")
}
}
}
close() {
this.goBack();
}
clear() {
this.capturedImageTitle = '';
this.seletedContent = [];
}
deletePublicationImage() {
this.publication.Files = []
}
setTitle() {
if (this.publicationType == ActionType.newRapid) {
this.publicationTitle = 'Nova Publicação Rápida';
}
else if (this.publicationType == ActionType.new) {
this.publicationTitle = 'Nova Publicação';
}
else if (this.publicationType == ActionType.edit) {
this.publicationTitle = 'Editar Publicação';
this.pub = this.publication;
}
}
async goBack() {
if (this.publicationType == ActionType.new) {
this.goBackToViewPublications.emit();
} else {
this.goBackToViewPublications.emit();
//this.goBacktoPublicationDetails.emit();
}
}
async compressImageBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> {
return new Promise((resolve, reject) => {
const image = new (window as any).Image();
image.src = base64String;
image.onload = async () => {
const canvas = document.createElement('canvas');
let newWidth = image.width;
let newHeight = image.height;
if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth;
newWidth = maxWidth;
}
if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight;
newHeight = maxHeight;
}
canvas.width = newWidth;
canvas.height = newHeight;
const context = canvas.getContext('2d');
context?.drawImage(image, 0, 0, newWidth, newHeight);
const compressedBase64 = canvas.toDataURL('image/jpeg', quality);
resolve(compressedBase64);
};
image.onerror = (error) => {
reject(error);
};
});
}
convertBlobToBase64(blob: Blob) {
console.log('Convert blob ',blob)
return new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result)
}
reader.readAsDataURL(blob)
},)
}
getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
removeTextBeforeSlash(inputString, mark) {
if (inputString.includes(mark)) {
const parts = inputString.split(mark);
return parts.length > 1 ? parts[1] : inputString;
} else {
return inputString;
}
}
async compressVideoBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> {
console.log(base64String)
return new Promise(async (resolve, reject) => {
try {
// Decode the base64 video string to an ArrayBuffer
const trimmedBase64 = base64String.trim();
const videoBuffer = this.base64ToArrayBuffer(this.removeTextBeforeSlash(trimmedBase64, ','));
// Create a Blob from the ArrayBuffer
const videoBlob = new Blob([videoBuffer], { type: 'video/mp4' });
// Create an object URL from the Blob
const videoObjectUrl = URL.createObjectURL(videoBlob);
// Create a video element
const video = document.createElement('video');
video.src = videoObjectUrl;
// Wait for the video to load metadata
video.addEventListener('loadedmetadata', async () => {
const canvas = document.createElement('canvas');
let newWidth = video.videoWidth;
let newHeight = video.videoHeight;
if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth;
newWidth = maxWidth;
}
if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight;
newHeight = maxHeight;
}
canvas.width = newWidth;
canvas.height = newHeight;
const context = canvas.getContext('2d');
// Start continuous rendering
function render() {
context?.drawImage(video, 0, 0, newWidth, newHeight);
requestAnimationFrame(render);
}
render();
// Convert the canvas to a Blob
canvas.toBlob(async (blob) => {
if (blob) {
// Read the Blob as an ArrayBuffer
const compressedVideoBuffer = await this.readBlobAsArrayBuffer(blob);
// Convert the ArrayBuffer back to base64
const compressedBase64 = this.arrayBufferToBase64(compressedVideoBuffer);
resolve(compressedBase64);
} else {
reject('Error creating compressed video blob.');
}
}, 'video/mp4', 0.5);
});
} catch (error) {
reject(error);
}
});
}
/* async compressVideoBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> {
return new Promise(async (resolve, reject) => {
try {
// Decode the base64 video string to an ArrayBuffer
const videoBuffer = this.base64ToArrayBuffer(this.removeTextBeforeSlash(base64String,','));
// Create a Blob from the ArrayBuffer
const videoBlob = new Blob([videoBuffer], { type: 'video/mp4' });
// Create an object URL from the Blob
const videoObjectUrl = URL.createObjectURL(videoBlob);
// Create a video element
const video = document.createElement('video');
// Create a source element and set its type attribute
const source = document.createElement('source');
source.type = 'video/mp4';
// Set the source URL
source.src = videoObjectUrl;
// Append the source element to the video element
video.appendChild(source);
// Wait for the video to load
video.addEventListener('loadedmetadata', async () => {
const canvas = document.createElement('canvas');
let newWidth = video.videoWidth;
let newHeight = video.videoHeight;
if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth;
newWidth = maxWidth;
}
if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight;
newHeight = maxHeight;
}
canvas.width = newWidth;
canvas.height = newHeight;
const context = canvas.getContext('2d');
// Create a function to draw each video frame onto the canvas
const drawFrame = () => {
context?.drawImage(video, 0, 0, newWidth, newHeight);
// Convert the canvas to a Blob with the correct MIME type
canvas.toBlob(async (blob) => {
if (blob) {
// Read the Blob as an ArrayBuffer
const compressedVideoBuffer = await this.readBlobAsArrayBuffer(blob);
// Convert the ArrayBuffer back to base64
const compressedBase64 = this.arrayBufferToBase64(compressedVideoBuffer);
resolve(compressedBase64);
} else {
reject('Error creating compressed video blob.');
}
}, 'video/mp4', quality);
// Request the next video frame
requestAnimationFrame(drawFrame);
};
// Start drawing frames
drawFrame();
// Start playing the video
video.play();
});
} catch (error) {
reject(error);
}
});
} */
/* async compressVideoBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> {
return new Promise(async (resolve, reject) => {
try {
// Decode the base64 video string to an ArrayBuffer
const videoBuffer = this.base64ToArrayBuffer(this.removeTextBeforeSlash(base64String,','));
// Create a Blob from the ArrayBuffer
const videoBlob = new Blob([videoBuffer], { type: 'video/mp4' });
// Create an object URL from the Blob
const videoObjectUrl = URL.createObjectURL(videoBlob);
// Create a video element
const video = document.createElement('video');
video.src = videoObjectUrl;
// Wait for the video to load metadata
video.addEventListener('loadedmetadata', async () => {
const canvas = document.createElement('canvas');
let newWidth = video.videoWidth;
let newHeight = video.videoHeight;
if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth;
newWidth = maxWidth;
}
if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight;
newHeight = maxHeight;
}
canvas.width = newWidth;
canvas.height = newHeight;
const context = canvas.getContext('2d');
context?.drawImage(video, 0, 0, newWidth, newHeight);
// Convert the canvas to a Blob with the correct MIME type
canvas.toBlob(async (blob) => {
if (blob) {
// Read the Blob as an ArrayBuffer
const compressedVideoBuffer = await this.readBlobAsArrayBuffer(blob);
// Convert the ArrayBuffer back to base64
const compressedBase64 = this.arrayBufferToBase64(compressedVideoBuffer);
resolve(compressedBase64);
} else {
reject('Error creating compressed video blob.');
}
}, 'video/mp4', quality);
});
} catch (error) {
reject(error);
}
});
} */
/* async compressVideoBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> {
return new Promise(async (resolve, reject) => {
try {
// Decode the base64 video string to an ArrayBuffer
const trimmedBase64 = base64String.trim();
console.log(this.removeTextBeforeSlash(trimmedBase64,','))
const videoBuffer = this.base64ToArrayBuffer(this.removeTextBeforeSlash(trimmedBase64,','));
// Create a Blob from the ArrayBuffer
const videoBlob = new Blob([videoBuffer], { type: 'video/mp4' });
// Create an object URL from the Blob
const videoObjectUrl = URL.createObjectURL(videoBlob);
// Create a video element
const video = document.createElement('video');
video.src = videoObjectUrl;
// Wait for the video to load metadata
video.addEventListener('loadedmetadata', async () => {
const canvas = document.createElement('canvas');
let newWidth = video.videoWidth;
let newHeight = video.videoHeight;
if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth;
newWidth = maxWidth;
}
if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight;
newHeight = maxHeight;
}
canvas.width = newWidth;
canvas.height = newHeight;
const context = canvas.getContext('2d');
context?.drawImage(video, 0, 0, newWidth, newHeight);
// Convert the canvas to a Blob
canvas.toBlob(async (blob) => {
if (blob) {
// Read the Blob as an ArrayBuffer
const compressedVideoBuffer = await this.readBlobAsArrayBuffer(blob);
// Convert the ArrayBuffer back to base64
const compressedBase64 = this.arrayBufferToBase64(compressedVideoBuffer);
resolve(compressedBase64);
} else {
reject('Error creating compressed video blob.');
}
}, 'video/mp4', quality);
});
} catch (error) {
reject(error);
}
});
} */
private base64ToArrayBuffer(base64: string): ArrayBuffer {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; ++i) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
private async readBlobAsArrayBuffer(blob: Blob): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
if (reader.result instanceof ArrayBuffer) {
resolve(reader.result);
} else {
reject('Error reading blob as ArrayBuffer.');
}
};
reader.readAsArrayBuffer(blob);
});
}
private arrayBufferToBase64(buffer: ArrayBuffer): string {
const binary = String.fromCharCode(...new Uint8Array(buffer));
return btoa(binary);
}
fileSizeToMB(sizeInBytes) {
var sizeInMB = (sizeInBytes / (1024 * 1024)).toFixed(2);
console.log(sizeInMB + 'MB');
return parseInt(sizeInMB)
}
deleteFromSeletedContent(index) {
this.seletedContent.splice(index, 1)
}
async uploadChunk() {
let time = new Date()
this.publication = {
DateIndex: time,
DocumentId: null,
ProcessId: this.folderId,
Title: this.pub.Title,
Message: this.pub.Message,
DatePublication: time,
OriginalFileName: this.capturedImageTitle || 'foto',
Files: this.seletedContent,
}
}
chossePhotoOrVideo() {
this.photoOrVideo = !this.photoOrVideo
}
async startVideoRecording() {
try {
let options: CaptureImageOptions = { limit: 1 }
const data: any = await this.mediaCapture.captureVideo(options)
this.video = data[0];
console.log(data)
data.forEach(async element => {
this.filesSizeSum = this.filesSizeSum + element.size
if (this.fileSizeToMB(this.filesSizeSum) <= 20) {
const savedFile = await Filesystem.copy({
from: element.fullPath, // directory prop removed, Capacitor parses filename for us
to: "video.mp4",
toDirectory: FilesystemDirectory.Data
});
console.log(savedFile.uri)
Filesystem.readFile({ path: savedFile.uri })
.then(async (content) => {
this.filecontent = true;
console.log('',content)
let fileObject = new PublicationAttachmentEntity({
base64: content.data,
extension: 'mp4',
OriginalFileName: 'record',
FileType: 'video'
}
)
this.seletedContent.push(fileObject)
})
.catch((err) => console.error(err));
} else {
if (this.seletedContent.length === 0)
this.filesSizeSum = 0
this.httpErrorHandle.validationMessagge('filessize')
}
});
} catch (error) {
console.log('record video error: ', error)
}
}
checkTableDivice() {
if (!this.platform.is('desktop'))
return true;
}
checkDesktop() {
if (this.platform.is('desktop'))
return true;
}
}
class UploadFileUseCase {
CMAPIService: CMAPIService = window["CMAPIAPIRepository"]
constructor() {}
async execute(PublicationAttachmentEntity: PublicationAttachmentEntity): Promise<Result<PublicationAttachmentEntity, PublicationAttachmentEntity>> {
return new Promise(async (resolve, reject) => {
let path: string;
const length = PublicationAttachmentEntity.chucksManager.chunks.totalChunks.toString()
const readAndUploadChunk = async(index: number) => {
const chunk = await PublicationAttachmentEntity.chucksManager.chunks.getChunks(index)
const blob = new Blob([chunk]);
const blobFile = new File([blob], "test.mp4", { type: blob.type });
return await this.CMAPIService.FileContent({length, path: PublicationAttachmentEntity.chucksManager.path, index, blobFile})
}
if(!PublicationAttachmentEntity.chucksManager.hasPath()) {
const initIndex = 1
const uploadRequest = await readAndUploadChunk(initIndex)
if(uploadRequest.isOk()) {
path = uploadRequest.value.data
PublicationAttachmentEntity.chucksManager.setPath(path)
PublicationAttachmentEntity.chucksManager.setResponse(initIndex, uploadRequest)
} else {
reject(err(PublicationAttachmentEntity))
}
}
const allRequest: Promise<any>[] = []
for (let index = 2; index <= PublicationAttachmentEntity.chucksManager.chunks.totalChunks -1; index++) {
const needUpload = PublicationAttachmentEntity.chucksManager.needToUploadChunkIndex(index)
if(needUpload) {
const request = readAndUploadChunk(index).then(async(uploadRequest) => {
if(uploadRequest.isErr()) {
const pingRequest = await this.CMAPIService.ping()
if( pingRequest.isErr()) {
reject(err(PublicationAttachmentEntity))
}
} else {
PublicationAttachmentEntity.chucksManager.setResponse(index, uploadRequest)
}
})
allRequest.push(request)
// const request = readAndUploadChunk(index)
// const uploadRequest = await request
// allRequest.push(request)
// if(uploadRequest.isErr()) {
// const pingRequest = await this.CMAPIService.ping()
// if( pingRequest.isErr()) {
// reject(err(PublicationAttachmentEntity))
// }
// } else {
// PublicationAttachmentEntity.chucksManager.setResponse(index, uploadRequest)
// }
}
}
await Promise.all(allRequest)
const uploadRequest = await readAndUploadChunk(PublicationAttachmentEntity.chucksManager.chunks.totalChunks)
if(uploadRequest.isErr()) {
const pingRequest = await this.CMAPIService.ping()
if( pingRequest.isErr()) {
reject(err(PublicationAttachmentEntity))
}
} else {
PublicationAttachmentEntity.chucksManager.setResponse(PublicationAttachmentEntity.chucksManager.chunks.totalChunks, uploadRequest)
}
PublicationAttachmentEntity.chucksManager.doneChunkUpload()
resolve(ok(PublicationAttachmentEntity))
})
}
}
class PublicationAttachmentEntity {
FileBase64: string
FileExtension: string
FileType: 'image' | 'video'
OriginalFileName: string
blobFile: File
toUpload = false;
chucksManager : ChucksManager
constructor({base64, extension, blobFile = null, OriginalFileName = null, FileType}) {
this.FileBase64 = base64;
this.FileExtension = extension;
this.blobFile = blobFile
this.OriginalFileName = OriginalFileName
this.FileType = FileType
this.fixFileBase64();
}
fixFileBase64() {
if(this.FileType == 'image' ) {
if(!this.FileBase64.startsWith('data:')) {
this.FileBase64 = 'data:image/jpg;base64,' + this.FileBase64
}
} else if (this.FileType == 'video' ) {
if(!this.FileBase64.startsWith('data:') && !this.FileBase64.startsWith('http')) {
this.FileBase64 = 'data:video/mp4;base64,' + this.FileBase64
}
}
}
needUpload() {
this.toUpload = true
}
setChunkManger (chunks: Chunks) {
this.chucksManager = new ChucksManager({chunks})
}
get hasChunkManger() {
return this.chucksManager?.chunks
}
get hasChunkManager() {
return this.chucksManager != null
}
}
interface IPublicationFormModelEntity {
DateIndex: any
DocumentId: any
ProcessId: any
Title: any
Message: any
DatePublication: any
Files: PublicationAttachmentEntity[]
}
class PublicationFormModel implements IPublicationFormModelEntity {
constructor() {}
DateIndex: any;
DocumentId: any;
ProcessId: any;
Title: any;
Message: any;
DatePublication: any;
OriginalFileName: string;
Files: PublicationAttachmentEntity[];
hasSet = false
setData(data: IPublicationFormModelEntity) {
if(!this.hasSet) {
Object.assign(this, data)
}
this.hasSet = true
}
}
class PublicationFormMV {
private UploadFileUseCase = new UploadFileUseCase()
private form = new PublicationFormModel()
private ObjectMergeNotification = new ObjectMergeNotification()
setDataToFrom(data: IPublicationFormModelEntity) {
this.form.setData(data)
}
private getVideoFiles() {
return this.form.Files.filter( x => x.FileType == 'video')
}
private upload(PublicationAttachmentEntity: PublicationAttachmentEntity) {
return new Promise(async (resolve, reject)=> {
if(!PublicationAttachmentEntity.hasChunkManger) {
const fileBlob = PublicationAttachmentEntity.blobFile;
const fileChunks = new Chunks({chunkSize: 500 })
fileChunks.setFile(fileBlob)
PublicationAttachmentEntity.setChunkManger(fileChunks)
PublicationAttachmentEntity.chucksManager.registerOnLastChunk(()=> {
const guid = PublicationAttachmentEntity.chucksManager.path
this.ObjectMergeNotification.subscribe(guid, (data) => {
// console.log("data", data)
PublicationAttachmentEntity
resolve(true)
})
})
} else {
if(PublicationAttachmentEntity.chucksManager.doneUpload) {
return resolve(true)
}
}
const result = await this.UploadFileUseCase.execute(PublicationAttachmentEntity)
if(result.isErr()) {
reject(false)
}
})
}
uploadVideosFiles(): Promise<Boolean> {
return new Promise((resolve, reject)=> {
const videosFiles = this.getVideoFiles()
const videosFilesToUploads = videosFiles.filter( e => e.toUpload == true)
const Promises: Promise<any>[] = []
for(const file of videosFilesToUploads) {
const promise = this.upload(file)
Promises.push(promise)
}
// Use Promise.all to wait for all promises to resolve
Promise.all(Promises)
.then((results) => {
// Check if every promise resolved successfully
const allPromisesResolvedSuccessfully = results.every((result) => result == true);
if (allPromisesResolvedSuccessfully) {
console.log('All promises resolved successfully.');
resolve(true)
} else {
reject(false)
console.log('Some promises failed to resolve successfully.');
}
})
.catch((error) => {
reject(false)
console.error('An error occurred while resolving promises:', error);
});
})
}
}
class Chunks {
chunkSize: number
private file: File
constructor({chunkSize}) {
this.chunkSize = chunkSize * 1024
}
get totalChunks () {
return Math.ceil(this.file.size / this.chunkSize);
}
// Function to read a chunk of the file
readChunk(start: number, end: number): Promise<ArrayBuffer> {
const file = this.file
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
if (reader.result instanceof ArrayBuffer) {
resolve(reader.result);
} else {
reject(new Error("Failed to read chunk"));
}
};
reader.readAsArrayBuffer(file.slice(start, end));
});
}
setFile(file: File) {
this.file = file
}
async getChunks(i: number) {
i--
if(i < this.totalChunks) {
const start = i * this.chunkSize;
const end = Math.min(start + this.chunkSize, this.file.size);
const chunk = await this.readChunk(start, end);
return chunk
}
}
}
interface IUploadResponse {
result: Result<any, Error>
attemp: number
}
class ChucksManager {
chunks: Chunks
uploads: {[key: string]: IUploadResponse } = {}
path: string = undefined
uploadPercentage: string = "0%"
merging = false
onSetPath: Function[] = []
onSetLastChunk: Function[] = []
contentReady = false
getUploadPercentage() {
return this.uploadPercentage
}
get uploadsCount() {
return Object.entries(this.uploads).length
}
get uploadWithSuccessCount() {
const uploadWithSuccess = Object.entries(this.uploads).filter(([index, data])=> data.result.isOk())
return uploadWithSuccess.length
}
get doneUpload() {
return this.chunks.totalChunks == this.uploadWithSuccessCount
}
uploadFunc: Function
constructor({chunks}) {
this.chunks = chunks
}
calculatePercentage(): number {
/**
* Calculate the percentage based on the total and current values.
*
* @param total - The total value.
* @param current - The current value.
* @returns The percentage calculated as (current / total) * 100.
*/
const total = this.chunks.totalChunks
const current = this.uploadWithSuccessCount
if (total === 0) {
return 0; // To avoid division by zero error
}
const percentage: number = (current / total) * 100;
return percentage;
}
setPercentage() {
const percentage: number = this.calculatePercentage()
console.log({percentage})
this.uploadPercentage = percentage.toString()+"%"
}
setPath(path: string) {
this.path = path
this.onSetPath.forEach(callback => callback());
}
registerOnSetPath(a: Function) {
this.onSetPath.push(a)
}
registerOnLastChunk(a: Function) {
this.onSetPath.push(a)
}
hasPath() {
return this.path != undefined
}
isIndexRegistered(index) {
if(!this.uploads[index]) {
return false
}
return true
}
needToUploadChunkIndex(index) {
return !this.uploads?.[index]?.result?.isOk()
}
setResponse(index, UploadResponse) {
if(!this.isIndexRegistered(index)) {
this.uploads[index] = {
attemp: 1,
result: UploadResponse
}
console.log({UploadResponse})
} else {
this.uploads[index].attemp++;
this.uploads[index].result = UploadResponse
}
this.setPercentage()
}
doneChunkUpload() {
this.merging = true
this.onSetLastChunk.forEach(callback => callback());
}
contentSetReady() {
this.merging = false
this.contentReady = true
}
}