Files
doneit-web/src/app/shared/publication/new-publication/new-publication.page.ts
T

886 lines
26 KiB
TypeScript
Raw Normal View History

2021-03-15 12:06:06 +01:00
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';
2021-06-15 15:09:20 +01:00
import { ToastService } from 'src/app/services/toast.service';
2021-07-06 12:26:45 +01:00
import { FormControl, FormGroup, Validators } from '@angular/forms';
2021-11-09 18:06:10 +01:00
import { ThemeService } from 'src/app/services/theme.service';
2023-11-10 15:37:12 +01:00
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
2023-02-27 09:34:36 +01:00
import { HttpErrorHandle } from 'src/app/services/http-error-handle.service';
2023-08-18 17:37:11 +01:00
import { PublicationFolderService } from 'src/app/store/publication-folder.service';
2023-11-10 15:37:12 +01:00
import { FilePicker } from '@capawesome/capacitor-file-picker';
2023-11-29 12:17:52 +01:00
import { checkFileTypeService } from 'src/app/services/checkFileType.service';
2024-01-18 13:08:10 +01:00
import { FileValidatorService } from "src/app/services/file/file-validator.service";
import { MiddlewareServiceService } from "src/app/shared/API/middleware/middleware-service.service";
2024-01-06 20:37:49 +01:00
import { LakefsRepositoryService } from '../../repository/lakefs/lakefs-repository.service';
2024-01-29 17:25:05 +01:00
2024-02-28 09:04:11 +01:00
import { SocketConnectionMCRService } from "src/app/services/socket-connection-mcr.service"
2024-01-29 13:49:53 +01:00
import { CMAPIService } from '../../repository/CMAPI/cmapi.service';
import { environment } from 'src/environments/environment';
2024-02-28 09:04:11 +01:00
import { CaptureImageOptions, MediaCapture } from '@awesome-cordova-plugins/media-capture/ngx';
2024-03-01 14:37:42 +01:00
import { Directory, Filesystem, FilesystemDirectory } from '@capacitor/filesystem';
2024-04-01 12:52:17 +01:00
import { ModalController, Platform } from '@ionic/angular';
2024-03-26 12:03:30 +01:00
import { PublicationAttachmentEntity } from '../upload/upload-streaming.service';
2024-03-01 14:37:42 +01:00
import { VideoconvertService } from 'src/app/services/videoconvert.service';
2024-03-26 12:03:30 +01:00
import { PublicationHolderService } from 'src/app/services/publication/publication-holder.service'
import { PublicationFromMvService } from "src/app/shared/publication/upload/publication-from-mv.service"
import { UploadStreamingService } from "src/app/shared/publication/upload/upload-streaming.service"
enum ActionType {
2024-01-06 20:37:49 +01:00
newRapid = "1",
new = "2",
edit = "3"
}
2023-08-18 17:37:11 +01:00
2021-03-15 12:06:06 +01:00
@Component({
selector: 'app-new-publication',
templateUrl: './new-publication.page.html',
styleUrls: ['./new-publication.page.scss'],
})
export class NewPublicationPage implements OnInit {
showLoader: boolean;
2023-11-10 15:37:12 +01:00
publicationTitle: string;
imgUrl: any;
Defaultimage: any = '';
2021-03-15 12:06:06 +01:00
2021-07-06 12:26:45 +01:00
Form: FormGroup;
validateFrom = false
2021-03-15 12:06:06 +01:00
2023-08-24 22:15:56 +01:00
@Input() publication!: Publication;
2024-04-22 16:51:58 +01:00
@Input() publicationType: ActionType;
2023-11-10 15:37:12 +01:00
@Input() folderId: string;
@Input() documentId: string;
2023-08-24 22:15:56 +01:00
2023-11-10 15:37:12 +01:00
@Output() closeDesktopComponent = new EventEmitter<any>();
2021-03-17 10:03:39 +01:00
@Output() openPublicationDetails = new EventEmitter<any>();
@Output() goBackToViewPublications = new EventEmitter<any>();
2023-11-10 15:37:12 +01:00
@Output() goBacktoPublicationDetails = new EventEmitter<any>();
2021-11-09 10:39:14 +01:00
2023-11-10 15:37:12 +01:00
guestPicture: any;
2021-03-15 12:06:06 +01:00
2023-11-10 15:37:12 +01:00
capturedImage: any = '';
capturedImageTitle: any = '';
fileType: string;
filecontent: boolean;
captureContent: any;
2023-11-29 12:17:52 +01:00
displayLimit = 4;
2023-12-06 17:01:00 +01:00
filesSizeSum = 0;
photoOrVideo: boolean = false;
video: any;
2021-03-15 12:06:06 +01:00
constructor(
2024-03-26 12:03:30 +01:00
public PublicationFromMvService: PublicationFromMvService,
2021-03-15 12:06:06 +01:00
public photoService: PhotoService,
private publications: PublicationsService,
2021-06-15 15:09:20 +01:00
private toastService: ToastService,
2023-02-27 09:34:36 +01:00
public ThemeService: ThemeService,
2023-08-18 17:37:11 +01:00
private httpErroHandle: HttpErrorHandle,
2023-11-29 12:17:52 +01:00
public PublicationFolderService: PublicationFolderService,
2023-11-29 16:06:56 +01:00
public checkFileType: checkFileTypeService,
2024-02-28 09:04:11 +01:00
private mediaCapture: MediaCapture,
private httpErrorHandle: HttpErrorHandle,
private platform: Platform,
2024-01-06 20:37:49 +01:00
private FileValidatorService: FileValidatorService,
private MiddlewareServiceService: MiddlewareServiceService,
2024-01-17 10:25:16 +01:00
private LakefsRepositoryService: LakefsRepositoryService,
private SocketConnectionMCRService: SocketConnectionMCRService,
2024-03-26 12:03:30 +01:00
private videoconvertService: VideoconvertService,
2024-04-01 12:52:17 +01:00
public UploadStreamingService: UploadStreamingService,
2024-04-01 16:55:26 +01:00
private modalController: ModalController
2021-08-23 16:06:05 +01:00
) {
this.publicationTitle = 'Nova Publicação';
2024-03-26 12:03:30 +01:00
2021-08-23 16:06:05 +01:00
}
2021-03-15 12:06:06 +01:00
ngOnInit() {
2024-04-02 11:57:29 +01:00
this.PublicationFromMvService.clear()
2024-02-28 09:04:11 +01:00
this.setAction();
2023-08-24 22:15:56 +01:00
this.setData()
2021-03-15 12:06:06 +01:00
}
2021-04-08 11:55:44 +01:00
2023-08-24 22:15:56 +01:00
setData() {
2024-02-28 09:04:11 +01:00
if(this.publication) {
this.processData(this.publication)
2023-08-18 17:37:11 +01:00
} else {
2023-08-28 17:06:16 +01:00
this.getPublicationDetail()
2023-08-18 17:37:11 +01:00
}
2021-04-08 11:55:44 +01:00
}
2023-08-28 17:06:16 +01:00
getPublicationDetail() {
2024-01-06 20:37:49 +01:00
if (this.publicationType != ActionType.new) {
2023-08-28 17:06:16 +01:00
this.showLoader = true;
2023-11-29 12:17:52 +01:00
this.publications.GetPublicationWithArrayOfFilesById(this.documentId).subscribe(res => {
2024-02-28 09:04:11 +01:00
this.processData(res)
2024-03-03 12:21:34 +01:00
console.log("res get", res)
2023-08-28 17:06:16 +01:00
this.showLoader = false;
2023-11-29 12:17:52 +01:00
}, (error) => {
console.log(error)
2023-08-28 17:06:16 +01:00
this.showLoader = false;
2023-11-10 15:37:12 +01:00
this.goBack()
2023-08-28 17:06:16 +01:00
});
}
}
2024-02-28 09:04:11 +01:00
processData(res) {
2024-03-03 12:21:34 +01:00
console.log("res process", res)
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files = []
this.PublicationFromMvService.form.setData({
2024-02-28 09:04:11 +01:00
DateIndex: res.DateIndex,
DocumentId: res.DocumentId,
ProcessId: res.ProcessId,
Title: res.Title,
Message: res.Message,
DatePublication: res.DatePublication
})
const newFiles: PublicationAttachmentEntity[] = res.Files.map(e => {
return new PublicationAttachmentEntity(
{
base64: e.FileBase64,
extension: e.FileExtension,
OriginalFileName: e.OriginalFileName,
FileType: this.checkFileType.checkFileType(e.FileExtension) as any
}
)
})
for(const files of newFiles) {
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files.push(files)
2024-02-28 09:04:11 +01:00
}
}
2021-11-09 10:39:14 +01:00
async takePicture() {
const capturedImage = await Camera.getPhoto({
2023-07-26 13:06:42 +01:00
quality: 50,
2021-11-09 10:39:14 +01:00
// allowEditing: true,
2022-02-11 15:08:27 +01:00
resultType: CameraResultType.Base64,
2021-11-09 10:39:14 +01:00
source: CameraSource.Camera
});
2023-11-10 15:37:12 +01:00
this.capturedImage = 'data:image/jpeg;base64,' + capturedImage.base64String;
this.capturedImageTitle = 'foto';
2024-04-01 12:52:17 +01:00
this.showCroppModal()
2023-11-29 16:06:56 +01:00
/* if(validation.isOk) { */
2024-04-01 12:52:17 +01:00
/* const compressedImage = await this.compressImageBase64(
2023-11-10 15:37:12 +01:00
this.capturedImage,
800, // maxWidth
800, // maxHeight
0.9 // quality
).then((picture) => {
this.photoOrVideo = false;
2024-01-06 20:37:49 +01:00
const FileExtension = this.removeTextBeforeSlash('jpeg', '/')
2024-01-06 20:37:49 +01:00
const newAttachment = new PublicationAttachmentEntity(
{
base64: picture,
extension: FileExtension,
OriginalFileName: "foto",
FileType: 'image'
}
)
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files.push(newAttachment)
2024-04-01 12:52:17 +01:00
}); */
2023-11-10 15:37:12 +01:00
}
2021-11-09 10:39:14 +01:00
2023-11-10 15:37:12 +01:00
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) => {
2024-01-06 20:37:49 +01:00
const FileExtension = this.removeTextBeforeSlash('jpeg', '/')
2024-01-06 20:37:49 +01:00
const newAttachment = new PublicationAttachmentEntity(
{
base64: picture,
extension: FileExtension,
OriginalFileName: "foto",
FileType: 'image'
}
)
//newAttachment.needUpload();
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files.push(newAttachment)
2023-11-10 15:37:12 +01:00
});
}
async loadVideo() {
2021-11-09 16:38:26 +01:00
2023-11-10 15:37:12 +01:00
const result = await FilePicker.pickMedia
({
multiple: true,
});
2023-12-06 17:01:00 +01:00
2024-01-31 17:13:07 +01:00
console.log(result)
2023-12-06 17:01:00 +01:00
2024-01-09 11:14:27 +01:00
result.files.forEach(async blobFile => {
console.log(blobFile)
2024-04-01 12:52:17 +01:00
if (this.checkFileType.checkFileType(blobFile.mimeType) == 'image') {
2024-01-29 08:25:27 +01:00
2024-01-31 17:12:01 +01:00
this.convertBlobToBase64(blobFile.blob).then((value: string) => {
2024-01-09 11:14:27 +01:00
this.filesSizeSum = this.filesSizeSum + blobFile.size
2024-04-01 15:59:08 +01:00
this.capturedImage = 'data:image/jpeg;base64,' + this.removeTextBeforeSlash(value, ','),
2024-04-01 12:52:17 +01:00
this.showCroppModal();
this.filecontent = true;
}).catch((erro) => {
console.log(erro)
})
} else if (this.checkFileType.checkFileType(blobFile.mimeType) == 'video'){
2024-05-17 15:27:02 +01:00
let convertedVideo = await this.videoconvertService.convertVideoWeb(blobFile.blob,"src/assets/videos/","output",'mp4')
2024-04-01 12:52:17 +01:00
this.convertBlobToBase64(blobFile.blob).then((value: string) => {
2024-01-06 20:37:49 +01:00
2024-04-01 12:52:17 +01:00
this.filesSizeSum = this.filesSizeSum + blobFile.size
2024-04-01 16:55:26 +01:00
const FileExtension = this.removeTextBeforeSlash(blobFile.mimeType, '/')
2024-01-06 20:37:49 +01:00
const file = new File([blobFile.blob], blobFile.name);
2024-01-17 10:25:16 +01:00
const newAttachment = new PublicationAttachmentEntity(
{
2024-01-31 17:13:07 +01:00
base64: this.removeTextBeforeSlash(value, ','),
2024-05-17 15:27:02 +01:00
extension: 'mp4',
blobFile: file,
2024-01-31 17:12:01 +01:00
FileType: this.checkFileType.checkFileType(FileExtension) as any,
OriginalFileName: 'load video'
}
)
2024-01-06 20:37:49 +01:00
2024-03-26 12:03:30 +01:00
newAttachment.needUpload()
this.PublicationFromMvService.form.Files.push(newAttachment)
this.filecontent = true;
2024-01-29 08:25:27 +01:00
}).catch((erro) => {
console.log(erro)
2023-11-29 12:17:52 +01:00
})
2024-04-01 16:55:26 +01:00
2023-11-10 15:37:12 +01:00
} else {
2023-11-29 12:17:52 +01:00
this.httpErroHandle.validationMessagge('filetype');
2023-11-10 15:37:12 +01:00
}
2024-01-06 20:37:49 +01:00
2023-11-29 12:17:52 +01:00
});
2024-02-28 09:04:11 +01:00
}
2021-11-09 16:38:26 +01:00
2024-01-29 08:25:27 +01:00
async loadVideoTablet() {
const result = await FilePicker.pickMedia
({
multiple: true,
});
2024-01-31 17:13:07 +01:00
console.log(result.files)
2024-01-29 08:25:27 +01:00
result.files.forEach(element => {
this.filesSizeSum = this.filesSizeSum + element.size
2024-04-01 12:52:17 +01:00
if (this.checkFileType.checkFileType(element.mimeType) == 'image') {
let resultUrl = decodeURIComponent(element.path);
try {
Filesystem.readFile({ path: resultUrl })
.then(async (content) => {
console.log(result)
this.capturedImage = 'data:image/jpeg;base64,'+content.data
this.showCroppModal()
})
.catch((err) => console.error(err));
} catch (error) {
console.log('upload video error: ', error)
}
} else if (this.checkFileType.checkFileType(element.mimeType) == 'video'){
2024-01-29 08:25:27 +01:00
let resultUrl = decodeURIComponent(element.path);
try {
Filesystem.readFile({ path: resultUrl })
.then(async (content) => {
console.log(result)
2024-01-31 17:13:07 +01:00
console.log('load video tablet base64', content)
2024-01-29 08:25:27 +01:00
this.filecontent = true;
2024-01-31 17:13:07 +01:00
let fileObject = new PublicationAttachmentEntity({
2024-04-03 15:28:58 +01:00
base64: content.data,
2024-01-29 08:25:27 +01:00
extension: this.removeTextBeforeSlash(element.mimeType, '/'),
OriginalFileName: 'video',
2024-01-31 17:12:01 +01:00
FileType: this.checkFileType.checkFileType( this.removeTextBeforeSlash(element.mimeType, '/')) as any
2024-01-29 08:25:27 +01:00
})
2024-03-03 12:21:34 +01:00
2024-04-09 09:20:49 +01:00
fileObject.needUpload()
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files.push(fileObject)
2024-01-29 08:25:27 +01:00
})
.catch((err) => console.error(err));
} catch (error) {
console.log('upload video error: ', error)
}
2024-04-01 12:52:17 +01:00
} else {
this.httpErroHandle.validationMessagge('filetype');
2024-01-29 08:25:27 +01:00
}
});
};
2021-07-06 12:26:45 +01:00
runValidation() {
2023-11-10 15:37:12 +01:00
this.validateFrom = true
2021-07-06 12:26:45 +01:00
}
injectValidation() {
this.Form = new FormGroup({
2024-03-26 12:03:30 +01:00
Subject: new FormControl(this.PublicationFromMvService.form.Title, [
2023-11-10 15:37:12 +01:00
Validators.required,
2021-07-06 12:26:45 +01:00
// Validators.minLength(4)
2021-07-15 15:39:10 +01:00
]),
2024-03-26 12:03:30 +01:00
Message: new FormControl(this.PublicationFromMvService.form.Message, [
2023-11-10 15:37:12 +01:00
Validators.required,
2021-07-15 15:39:10 +01:00
Validators.maxLength(1000)
2021-07-06 12:26:45 +01:00
])
})
}
2021-07-14 19:04:33 +01:00
async save() {
2021-07-06 12:26:45 +01:00
this.injectValidation()
this.runValidation()
2023-11-10 15:37:12 +01:00
if (this.Form.invalid) {
2023-02-27 09:34:36 +01:00
return false
}
2024-01-19 09:42:24 +01:00
2024-04-22 16:51:58 +01:00
this.PublicationFromMvService.setFolderId(this.folderId)
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.setFolderId(this.folderId)
this.goBack();
await this.PublicationFromMvService.save()
2024-01-19 09:42:24 +01:00
2024-03-26 12:03:30 +01:00
// this.PublicationHolderService.setPublication(this.PublicationFromMvService)
2024-01-31 17:12:01 +01:00
}
ngOnDestroy() {
2024-03-26 14:20:14 +01:00
if(!this.PublicationFromMvService.form.send) {
this.PublicationFromMvService.cancel()
}
2021-03-15 12:06:06 +01:00
}
2024-03-26 12:03:30 +01:00
2023-11-10 15:37:12 +01:00
close() {
2024-04-09 09:20:49 +01:00
this.PublicationFromMvService.form.cancel = true
2024-04-01 16:55:26 +01:00
if(this.PublicationFromMvService.form.send == false) {
this.PublicationFromMvService.cancel()
this.PublicationFromMvService.ObjectMergeNotification.close()
}
2021-03-17 10:03:39 +01:00
this.goBack();
2021-03-15 12:06:06 +01:00
}
2021-11-10 15:51:27 +01:00
2023-08-15 10:15:08 +01:00
clear() {
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files = [];
2021-03-15 12:06:06 +01:00
}
2023-08-15 10:15:08 +01:00
deletePublicationImage() {
2023-11-10 15:37:12 +01:00
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files = []
2023-08-15 10:15:08 +01:00
}
2024-02-28 09:04:11 +01:00
setAction() {
2024-01-06 20:37:49 +01:00
if (this.publicationType == ActionType.newRapid) {
2021-03-15 12:06:06 +01:00
this.publicationTitle = 'Nova Publicação Rápida';
}
2024-01-06 20:37:49 +01:00
else if (this.publicationType == ActionType.new) {
2021-03-15 12:06:06 +01:00
this.publicationTitle = 'Nova Publicação';
}
2024-01-06 20:37:49 +01:00
else if (this.publicationType == ActionType.edit) {
2021-03-15 12:06:06 +01:00
this.publicationTitle = 'Editar Publicação';
}
2024-04-22 16:51:58 +01:00
this.PublicationFromMvService.publicationType = this.publicationType
2021-03-15 12:06:06 +01:00
}
2023-11-10 15:37:12 +01:00
async goBack() {
2021-11-09 10:39:14 +01:00
2024-01-06 20:37:49 +01:00
if (this.publicationType == ActionType.new) {
2021-03-17 10:03:39 +01:00
this.goBackToViewPublications.emit();
} else {
2021-04-08 11:55:44 +01:00
this.goBackToViewPublications.emit();
//this.goBacktoPublicationDetails.emit();
2021-03-17 10:03:39 +01:00
}
2021-11-09 10:39:14 +01:00
}
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;
2023-11-10 15:37:12 +01:00
image.onload = async () => {
const canvas = document.createElement('canvas');
let newWidth = image.width;
let newHeight = image.height;
2023-11-10 15:37:12 +01:00
if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth;
newWidth = maxWidth;
}
2023-11-10 15:37:12 +01:00
if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight;
newHeight = maxHeight;
}
2023-11-10 15:37:12 +01:00
canvas.width = newWidth;
canvas.height = newHeight;
2023-11-10 15:37:12 +01:00
const context = canvas.getContext('2d');
context?.drawImage(image, 0, 0, newWidth, newHeight);
2023-11-10 15:37:12 +01:00
const compressedBase64 = canvas.toDataURL('image/jpeg', quality);
resolve(compressedBase64);
};
2023-11-10 15:37:12 +01:00
image.onerror = (error) => {
reject(error);
};
});
}
2023-11-10 15:37:12 +01:00
convertBlobToBase64(blob: Blob) {
2024-01-31 17:13:07 +01:00
try {
return new Promise((resolve, reject) => {
const chunkSize = 5000000; // 5 MB
const fileSize = blob.size;
const chunks = Math.ceil(fileSize / chunkSize);
let currentChunk = 0;
const base64Chunks = [];
const reader = new FileReader();
reader.onload = function () {
base64Chunks.push(reader.result);
currentChunk++;
if (currentChunk < chunks) {
loadNextChunk();
} else {
const base64Data = base64Chunks.join("");
resolve(base64Data);
}
};
reader.onerror = function (error) {
reject(error);
};
function loadNextChunk() {
const start = currentChunk * chunkSize;
const end = Math.min(start + chunkSize, fileSize);
const chunk = blob.slice(start, end);
reader.readAsDataURL(chunk);
}
loadNextChunk();
});
} catch (error) {
console.log(error);
}
2023-11-10 15:37:12 +01:00
}
2024-01-31 17:13:07 +01:00
/* 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)
},)
} */
2024-01-29 08:25:27 +01:00
getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
2024-01-31 17:13:07 +01:00
}
2024-01-29 08:25:27 +01:00
removeTextBeforeSlash(inputString, mark) {
2023-12-06 17:01:00 +01:00
if (inputString.includes(mark)) {
const parts = inputString.split(mark);
2023-11-29 12:17:52 +01:00
return parts.length > 1 ? parts[1] : inputString;
} else {
return inputString;
}
}
2023-12-06 17:01:00 +01:00
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, ','));
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
// Create a Blob from the ArrayBuffer
const videoBlob = new Blob([videoBuffer], { type: 'video/mp4' });
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
// Create an object URL from the Blob
const videoObjectUrl = URL.createObjectURL(videoBlob);
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
// Create a video element
const video = document.createElement('video');
video.src = videoObjectUrl;
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
// Wait for the video to load metadata
video.addEventListener('loadedmetadata', async () => {
const canvas = document.createElement('canvas');
let newWidth = video.videoWidth;
let newHeight = video.videoHeight;
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth;
newWidth = maxWidth;
}
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight;
newHeight = maxHeight;
}
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
canvas.width = newWidth;
canvas.height = newHeight;
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
const context = canvas.getContext('2d');
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
// Start continuous rendering
function render() {
context?.drawImage(video, 0, 0, newWidth, newHeight);
requestAnimationFrame(render);
}
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
render();
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
// Convert the canvas to a Blob
canvas.toBlob(async (blob) => {
if (blob) {
// Read the Blob as an ArrayBuffer
const compressedVideoBuffer = await this.readBlobAsArrayBuffer(blob);
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
// Convert the ArrayBuffer back to base64
const compressedBase64 = this.arrayBufferToBase64(compressedVideoBuffer);
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
resolve(compressedBase64);
} else {
reject('Error creating compressed video blob.');
}
}, 'video/mp4', 0.5);
});
} catch (error) {
reject(error);
}
});
}
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
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;
}
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
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);
});
}
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
private arrayBufferToBase64(buffer: ArrayBuffer): string {
const binary = String.fromCharCode(...new Uint8Array(buffer));
return btoa(binary);
}
2024-01-06 20:37:49 +01:00
2023-12-06 17:01:00 +01:00
fileSizeToMB(sizeInBytes) {
var sizeInMB = (sizeInBytes / (1024 * 1024)).toFixed(2);
console.log(sizeInMB + 'MB');
return parseInt(sizeInMB)
}
2023-11-10 15:37:12 +01:00
2024-01-06 20:37:49 +01:00
deleteFromSeletedContent(index) {
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files.splice(index, 1)
2024-01-24 10:08:21 +01:00
}
2024-01-06 20:37:49 +01:00
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) {
2024-03-03 12:22:34 +01:00
if(this.platform.is('ios')) {
this.recordevideoIos(element.fullPath)
} else {
this.recordVideoPc(element.fullPath)
}
} else {
2024-03-26 12:03:30 +01:00
if (this.PublicationFromMvService.form.Files.length === 0)
this.filesSizeSum = 0
this.httpErrorHandle.validationMessagge('filessize')
}
});
} catch (error) {
console.log('record video error: ', error)
}
}
checkTableDivice() {
2024-01-31 17:13:07 +01:00
if (this.platform.is('tablet'))
return true;
}
2024-01-29 08:25:27 +01:00
checkDesktop() {
if (this.platform.is('desktop'))
return true;
}
2024-03-01 14:37:42 +01:00
async recordevideoIos(fullPath) {
try {
const directory = await Filesystem.getUri({
directory: Directory.Cache,
path: '',
});
2024-03-03 09:25:04 +01:00
const stringGerada = this.gerarStringAleatoria();
console.log(stringGerada);
this.videoconvertService.convertVideo(fullPath,directory.uri,stringGerada,'mp4');
2024-03-01 14:37:42 +01:00
2024-03-14 09:10:17 +01:00
Filesystem.readFile({ path: `${directory.uri}${stringGerada}.mp4`})
2024-03-01 14:37:42 +01:00
.then(async (content) => {
this.filecontent = true;
console.log('', content)
let fileObject = new PublicationAttachmentEntity({
2024-03-03 18:23:44 +01:00
base64: 'data:video/mp4;base64,'+content.data,
2024-03-01 14:37:42 +01:00
extension: 'mp4',
OriginalFileName: 'record',
FileType: 'video'
}
)
2024-03-03 18:23:44 +01:00
/* fileObject.needUpload() */
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files.push(fileObject)
2024-03-01 14:37:42 +01:00
})
.catch((erro) => console.error('read converted video erro ', erro));
} catch (error) {
console.log('record video ios erro, ', error)
}
}
async recordVideoPc(fullPath) {
try {
const savedFile = await Filesystem.copy({
from: 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)
2024-03-04 06:07:58 +01:00
let fileObject;
if(this.platform.is('desktop')) {
2024-03-04 06:07:58 +01:00
fileObject = new PublicationAttachmentEntity({
base64: content.data,
extension: 'mp4',
OriginalFileName: 'record',
FileType: 'video'
2024-03-04 06:07:58 +01:00
})
} else {
fileObject = new PublicationAttachmentEntity({
base64: 'data:video/mp4;base64,'+content.data,
extension: 'mp4',
OriginalFileName: 'record',
FileType: 'video'
2024-03-04 06:07:58 +01:00
})
2024-03-01 14:37:42 +01:00
}
2024-03-03 18:23:44 +01:00
/* fileObject.needUpload() */
2024-03-26 12:03:30 +01:00
this.PublicationFromMvService.form.Files.push(fileObject)
2024-03-01 14:37:42 +01:00
})
.catch((err) => console.error(err));
} catch (error) {
}
}
2024-03-03 09:25:04 +01:00
gerarStringAleatoria() {
const caracteres = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let stringAleatoria = '';
for (let i = 0; i < 4; i++) {
const indiceAleatorio = Math.floor(Math.random() * caracteres.length);
stringAleatoria += caracteres.charAt(indiceAleatorio);
}
return stringAleatoria;
}
2024-04-01 12:52:17 +01:00
2024-04-09 09:20:49 +01:00
async showCroppModal() {
2024-04-01 12:52:17 +01:00
2024-04-09 11:28:08 +01:00
const modal = await this.modalController.create({
component: CropImagePage,
componentProps: {
base64ToCroppe: this.capturedImage
},
cssClass: 'modal modal-desktop'
});
modal.onDidDismiss().then((res) => {
if (res) {
this.capturedImage = res.data
this.filecontent = true;
this.photoOrVideo = false;
const newAttachment = new PublicationAttachmentEntity(
{
base64: res.data.base64ToCroppe,
extension: 'jpeg',
OriginalFileName: "image",
FileType: 'image'
}
)
this.PublicationFromMvService.form.Files.push(newAttachment)
}
}, (error) => {
console.log(error)
});
await modal.present();
// let fileObject = new PublicationAttachmentEntity({
// base64: this.removeTextBeforeSlash(this.capturedImage, ',') ,
// extension: 'jpeg',
// OriginalFileName: 'video',
// FileType: 'image'
// })
// this.PublicationFromMvService.form.Files.push(fileObject)
2024-04-01 12:52:17 +01:00
2024-04-09 09:20:49 +01:00
}
2024-01-06 20:37:49 +01:00
}
2024-02-28 09:04:11 +01:00
import { Observable, of, Subject } from 'rxjs';
import { tap, switchMap, delay, map } from 'rxjs/operators';
2024-04-01 12:52:17 +01:00
import { CropImagePage } from 'src/app/modals/crop-image/crop-image.page';
2024-02-28 09:04:11 +01:00
function shareResponse<T>(): MethodDecorator {
return function (
target: any,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
): PropertyDescriptor {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]): Observable<T> {
// Create a subject to broadcast the response
const responseSubject = new Subject<T>();
// Use switchMap to ensure only one subscription is active at a time
return responseSubject.pipe(
switchMap(() => {
// If no ongoing execution, trigger the original method
if (!this.isExecuting) {
this.isExecuting = true;
// Call the original method
const result = originalMethod.apply(this, args);
// Convert the result to an observable if it's not already
const resultObservable = result instanceof Observable ? result : of(result);
// Tap into the result to broadcast it to all subscribers
return resultObservable.pipe(
tap((response) => {
responseSubject.next(response);
this.isExecuting = false;
})
);
} else {
// If ongoing execution, return an empty observable
return of();
}
})
);
};
return descriptor;
};
}
class ApiService {
private isExecuting = false;
@shareResponse<number>()
fetchData(): Observable<number> {
// Simulate fetching data locally (replace it with your own data source)
const localData: number[] = [1, 2, 3, 4, 5];
return of(localData.reduce((sum, value) => sum + value, 0));
}
}
const apiService = new ApiService();
// Example usage
apiService.fetchData().subscribe((result) => console.log('Subscriber 1:', result));
// This subscriber will receive the same result without triggering a new execution
apiService.fetchData().subscribe((result) => console.log('Subscriber 2:', result));