record video on diferente divice solved

This commit is contained in:
Eudes Inácio
2024-01-26 05:59:14 +01:00
parent 892bdbe5cf
commit 300b488174
6 changed files with 487 additions and 405 deletions
+2 -1
View File
@@ -19,7 +19,8 @@
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme" android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"> android:usesCleartextTraffic="true"
android:requestLegacyExternalStorage="true">
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
File diff suppressed because one or more lines are too long
@@ -100,41 +100,26 @@
</div> </div>
<!-- Current -->
<!-- <div *ngIf="!captureContent">
<div class="ion-item-container-no-border mb-20"
*ngIf="publication && !( publication.FileBase64 == 'data:image/jpg;base64,null' || publication.FileBase64 == '' ) && !capturedImage">
<ion-label class="attached-title pb-10">Fotografia Anexada</ion-label>
<div class="d-flex justify-content-between">
<div class="d-flex">
<ion-thumbnail slot="start">
<ion-img [(ngModel)]="publication.FileBase64" name="image" ngDefaultControl
[src]="publication.FileBase64"></ion-img>
</ion-thumbnail>
<ion-label class="pl-10">
<p>{{publication.OriginalFileName}}.{{publication.FileExtension}}</p>
<p hidden>size</p>
</ion-label>
</div>
<button class="btn-no-color" (click)="deletePublicationImage()">
<ion-icon name="close"></ion-icon>
</button>
</div>
</div>
</div> -->
<div class="hide-desktop"> <div style="display: flex;">
<ion-label (click)="loadVideo()"> <div (click)="chossePhotoOrVideo()">
<div class="attach-icon"> <div class="attach-icon">
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " src="assets/images/icons-add-photo.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'default' "
src="assets/images/icons-add-photo.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " <ion-icon *ngIf="ThemeService.currentTheme == 'gov' "
src="assets/images/theme/gov/icons-add-photo.svg"></ion-icon> src="assets/images/theme/gov/icons-add-photo.svg"></ion-icon>
</div> </div>
<div class="attach-document cursor-pointer"> <div class="attach-document">
<ion-label>Tirar Fotografia</ion-label> <ion-label>Câmera</ion-label>
</div> </div>
</ion-label> </div>
</div>
<div *ngIf="photoOrVideo" class="container-multiselect pt-10" style="width: 200px;">
<button id="container-multiselect" class="multiselect-button" (click)="takePicture()">Fotografia</button>
<button id="container-multiselect" class="multiselect-button" (click)="startVideoRecording()">Video</button>
</div> </div>
<div > <div >
@@ -145,7 +130,7 @@
src="assets/images/theme/gov/icons-add-photos.svg"></ion-icon> src="assets/images/theme/gov/icons-add-photos.svg"></ion-icon>
</div> </div>
<div class="attach-document cursor-pointer"> <div class="attach-document cursor-pointer">
<ion-label>Anexar Fotografia</ion-label> <ion-label>Galeria</ion-label>
</div> </div>
</ion-label> </ion-label>
</div> </div>
@@ -156,6 +156,10 @@ font-size: rem(25);
display: block; display: block;
} }
.container-multiselect {
display: grid;
}
@@ -16,8 +16,11 @@ import { LakefsRepositoryService } from '../../repository/lakefs/lakefs-reposito
import { ok, err, Result } from 'neverthrow'; import { ok, err, Result } from 'neverthrow';
import { SocketConnectionMCRService } from "src/app/services/socket-connection-mcr.service" import { SocketConnectionMCRService } from "src/app/services/socket-connection-mcr.service"
import { CMAPIService } from "src/app/shared/repository/CMAPI/cmapi.service"; import { CMAPIService } from "src/app/shared/repository/CMAPI/cmapi.service";
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';
enum ActionType { enum ActionType {
newRapid = "1", newRapid = "1",
new = "2", new = "2",
edit = "3" edit = "3"
@@ -60,6 +63,8 @@ export class NewPublicationPage implements OnInit {
seletedContent: PublicationAttachmentEntity[] = [] seletedContent: PublicationAttachmentEntity[] = []
displayLimit = 4; displayLimit = 4;
filesSizeSum = 0; filesSizeSum = 0;
photoOrVideo: boolean = false;
video: any;
publicationFormMV = new PublicationFormMV() publicationFormMV = new PublicationFormMV()
@@ -76,7 +81,10 @@ export class NewPublicationPage implements OnInit {
private MiddlewareServiceService: MiddlewareServiceService, private MiddlewareServiceService: MiddlewareServiceService,
private LakefsRepositoryService: LakefsRepositoryService, private LakefsRepositoryService: LakefsRepositoryService,
private SocketConnectionMCRService: SocketConnectionMCRService, private SocketConnectionMCRService: SocketConnectionMCRService,
private CMAPIService: CMAPIService private CMAPIService: CMAPIService,
private mediaCapture: MediaCapture,
private httpErrorHandle: HttpErrorHandle,
private platform: Platform,
) { ) {
this.publicationTitle = 'Nova Publicação'; this.publicationTitle = 'Nova Publicação';
@@ -134,9 +142,9 @@ export class NewPublicationPage implements OnInit {
OriginalFileName: res.OriginalFileName, OriginalFileName: res.OriginalFileName,
FileExtension: res.FileExtension, FileExtension: res.FileExtension,
} }
console.log('edit',this.publication) console.log('edit', this.publication)
this.pub = this.publication; this.pub = this.publication;
this.seletedContent = this.publication.Files.map( e => { this.seletedContent = this.publication.Files.map(e => {
return new PublicationAttachmentEntity( return new PublicationAttachmentEntity(
{ {
base64: e.FileBase64, base64: e.FileBase64,
@@ -173,12 +181,13 @@ export class NewPublicationPage implements OnInit {
800, // maxHeight 800, // maxHeight
0.9 // quality 0.9 // quality
).then((picture) => { ).then((picture) => {
this.photoOrVideo = false;
let fileObject = { let fileObject = {
FileBase64: picture, FileBase64: picture,
FileExtension: this.removeTextBeforeSlash('jpeg','/') FileExtension: this.removeTextBeforeSlash('jpeg', '/')
} }
const FileExtension = this.removeTextBeforeSlash('jpeg','/') const FileExtension = this.removeTextBeforeSlash('jpeg', '/')
const newAttachment = new PublicationAttachmentEntity( const newAttachment = new PublicationAttachmentEntity(
{ {
@@ -194,9 +203,9 @@ export class NewPublicationPage implements OnInit {
this.seletedContent.push(newAttachment) this.seletedContent.push(newAttachment)
}); });
/* } else { /* } else {
this.toastService._badRequest("Imagem inválida") this.toastService._badRequest("Imagem inválida")
} */ } */
} }
async laodPicture() { async laodPicture() {
@@ -219,10 +228,10 @@ export class NewPublicationPage implements OnInit {
).then((picture) => { ).then((picture) => {
let fileObject = { let fileObject = {
FileBase64: picture, FileBase64: picture,
FileExtension: this.removeTextBeforeSlash('jpeg','/') FileExtension: this.removeTextBeforeSlash('jpeg', '/')
} }
const FileExtension = this.removeTextBeforeSlash('jpeg','/') const FileExtension = this.removeTextBeforeSlash('jpeg', '/')
const newAttachment = new PublicationAttachmentEntity( const newAttachment = new PublicationAttachmentEntity(
{ {
@@ -246,36 +255,41 @@ export class NewPublicationPage implements OnInit {
multiple: true, multiple: true,
}); });
console.log(result)
result.files.forEach(async blobFile => { result.files.forEach(async blobFile => {
if(this.checkFileType.checkFileType(blobFile.mimeType) == 'image' || this.checkFileType.checkFileType(blobFile.mimeType) == 'video') { console.log(blobFile)
if (this.checkFileType.checkFileType(blobFile.mimeType) == 'image' || this.checkFileType.checkFileType(blobFile.mimeType) == 'video') {
console.log()
this.convertBlobToBase64(blobFile.blob).then((value) => { this.convertBlobToBase64(blobFile.blob).then((value) => {
this.filesSizeSum = this.filesSizeSum + blobFile.size this.filesSizeSum = this.filesSizeSum + blobFile.size
if(this.fileSizeToMB(this.filesSizeSum) <= 20) { if (this.fileSizeToMB(this.filesSizeSum) <= 20) {
const FileExtension = this.removeTextBeforeSlash(blobFile.mimeType,'/') const FileExtension = this.removeTextBeforeSlash(blobFile.mimeType, '/')
const file = new File([blobFile.blob], blobFile.name); const file = new File([blobFile.blob], blobFile.name);
const newAttachment = new PublicationAttachmentEntity( const newAttachment = new PublicationAttachmentEntity(
{ {
base64: value, base64: value,
extension: FileExtension, extension: FileExtension,
blobFile: file, blobFile: file,
FileType: this.checkFileType.checkFileType(FileExtension) FileType: this.checkFileType.checkFileType(FileExtension)
} }
) )
newAttachment.needUpload() newAttachment.needUpload()
this.seletedContent.push(newAttachment) this.seletedContent.push(newAttachment)
this.filecontent = true; console.log(this.seletedContent)
} else { this.filecontent = true;
if(this.seletedContent.length === 0) } else {
this.filesSizeSum = 0 if (this.seletedContent.length === 0)
this.filesSizeSum = 0
this.httpErroHandle.validationMessagge('filessize'); this.httpErroHandle.validationMessagge('filessize');
} }
}) })
} else { } else {
this.httpErroHandle.validationMessagge('filetype'); this.httpErroHandle.validationMessagge('filetype');
@@ -338,7 +352,7 @@ export class NewPublicationPage implements OnInit {
} }
if(this.seletedContent.length == 0) { if (this.seletedContent.length == 0) {
const newAttachment = new PublicationAttachmentEntity( const newAttachment = new PublicationAttachmentEntity(
{ {
@@ -370,7 +384,7 @@ export class NewPublicationPage implements OnInit {
} }
this.publication.Files = this.publication.Files.map( e => ({ this.publication.Files = this.publication.Files.map(e => ({
FileBase64: e.FileBase64, FileBase64: e.FileBase64,
FileExtension: e.FileExtension, FileExtension: e.FileExtension,
OriginalFileName: 'foto' OriginalFileName: 'foto'
@@ -417,7 +431,7 @@ export class NewPublicationPage implements OnInit {
this.publication.Files = this.publication.Files.map( e => ({ this.publication.Files = this.publication.Files.map(e => ({
FileBase64: e.FileBase64, FileBase64: e.FileBase64,
FileExtension: e.FileExtension, FileExtension: e.FileExtension,
OriginalFileName: 'foto' OriginalFileName: 'foto'
@@ -529,6 +543,7 @@ export class NewPublicationPage implements OnInit {
} }
convertBlobToBase64(blob: Blob) { convertBlobToBase64(blob: Blob) {
console.log('Convert blob ',blob)
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const reader = new FileReader; const reader = new FileReader;
reader.onerror = reject; reader.onerror = reject;
@@ -539,7 +554,7 @@ export class NewPublicationPage implements OnInit {
}) })
} }
removeTextBeforeSlash(inputString,mark) { removeTextBeforeSlash(inputString, mark) {
if (inputString.includes(mark)) { if (inputString.includes(mark)) {
const parts = inputString.split(mark); const parts = inputString.split(mark);
return parts.length > 1 ? parts[1] : inputString; return parts.length > 1 ? parts[1] : inputString;
@@ -618,57 +633,195 @@ export class NewPublicationPage implements OnInit {
/* async compressVideoBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> { /* async compressVideoBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise<string> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
// Decode the base64 video string to an ArrayBuffer // Decode the base64 video string to an ArrayBuffer
const videoBuffer = this.base64ToArrayBuffer(this.removeTextBeforeSlash(base64String,',')); const videoBuffer = this.base64ToArrayBuffer(this.removeTextBeforeSlash(base64String,','));
// Create a Blob from the ArrayBuffer // Create a Blob from the ArrayBuffer
const videoBlob = new Blob([videoBuffer], { type: 'video/mp4' }); const videoBlob = new Blob([videoBuffer], { type: 'video/mp4' });
// Create an object URL from the Blob // Create an object URL from the Blob
const videoObjectUrl = URL.createObjectURL(videoBlob); const videoObjectUrl = URL.createObjectURL(videoBlob);
// Create a video element // Create a video element
const video = document.createElement('video'); const video = document.createElement('video');
// Create a source element and set its type attribute // Create a source element and set its type attribute
const source = document.createElement('source'); const source = document.createElement('source');
source.type = 'video/mp4'; source.type = 'video/mp4';
// Set the source URL // Set the source URL
source.src = videoObjectUrl; source.src = videoObjectUrl;
// Append the source element to the video element // Append the source element to the video element
video.appendChild(source); video.appendChild(source);
// Wait for the video to load // Wait for the video to load
video.addEventListener('loadedmetadata', async () => { video.addEventListener('loadedmetadata', async () => {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
let newWidth = video.videoWidth; let newWidth = video.videoWidth;
let newHeight = video.videoHeight; let newHeight = video.videoHeight;
if (newWidth > maxWidth) { if (newWidth > maxWidth) {
newHeight *= maxWidth / newWidth; newHeight *= maxWidth / newWidth;
newWidth = maxWidth; newWidth = maxWidth;
} }
if (newHeight > maxHeight) { if (newHeight > maxHeight) {
newWidth *= maxHeight / newHeight; newWidth *= maxHeight / newHeight;
newHeight = maxHeight; newHeight = maxHeight;
} }
canvas.width = newWidth; canvas.width = newWidth;
canvas.height = newHeight; canvas.height = newHeight;
const context = canvas.getContext('2d'); const context = canvas.getContext('2d');
// Create a function to draw each video frame onto the canvas // Create a function to draw each video frame onto the canvas
const drawFrame = () => { 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); context?.drawImage(video, 0, 0, newWidth, newHeight);
// Convert the canvas to a Blob with the correct MIME type // Convert the canvas to a Blob
canvas.toBlob(async (blob) => { canvas.toBlob(async (blob) => {
if (blob) { if (blob) {
// Read the Blob as an ArrayBuffer // Read the Blob as an ArrayBuffer
@@ -683,151 +836,13 @@ export class NewPublicationPage implements OnInit {
} }
}, 'video/mp4', quality); }, 'video/mp4', quality);
// Request the next video frame });
requestAnimationFrame(drawFrame);
};
// Start drawing frames } catch (error) {
drawFrame(); reject(error);
}
// 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 { private base64ToArrayBuffer(base64: string): ArrayBuffer {
const binaryString = window.atob(base64); const binaryString = window.atob(base64);
@@ -890,6 +905,58 @@ export class NewPublicationPage implements OnInit {
this.publicationFormMV.uploadVideosFiles() this.publicationFormMV.uploadVideosFiles()
} }
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;
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;
}
} }
// class UploadFileUseCase { // class UploadFileUseCase {
@@ -994,32 +1061,32 @@ export class NewPublicationPage implements OnInit {
class UploadFileUseCase { class UploadFileUseCase {
CMAPIService: CMAPIService = window["CMAPIService"] CMAPIService: CMAPIService = window["CMAPIService"]
constructor() {} constructor() { }
async execute(ChucksManager: ChucksManager): Promise<Result<ChucksManager, ChucksManager>> { async execute(ChucksManager: ChucksManager): Promise<Result<ChucksManager, ChucksManager>> {
let path: string; let path: string;
const length = ChucksManager.chunks.totalChunks.toString() const length = ChucksManager.chunks.totalChunks.toString()
const readAndUploadChunk = async(index: number) => { const readAndUploadChunk = async (index: number) => {
const chunk = await ChucksManager.chunks.getChunks(index) const chunk = await ChucksManager.chunks.getChunks(index)
const blob = new Blob([chunk]); const blob = new Blob([chunk]);
const blobFile = new File([blob], "test.mp4", { type: blob.type }); const blobFile = new File([blob], "test.mp4", { type: blob.type });
return await this.CMAPIService.FileContent({length, path: ChucksManager.path, index, blobFile}) return await this.CMAPIService.FileContent({ length, path: ChucksManager.path, index, blobFile })
} }
if(!ChucksManager.hasPath()) { if (!ChucksManager.hasPath()) {
const initIndex = ChucksManager.uploadsCount + 1 const initIndex = ChucksManager.uploadsCount + 1
const chuck = await ChucksManager.chunks.getChunks(initIndex) const chuck = await ChucksManager.chunks.getChunks(initIndex)
const blob = new Blob([chuck]); const blob = new Blob([chuck]);
const blobFile = new File([blob], "test.mp4", { type: blob.type }); const blobFile = new File([blob], "test.mp4", { type: blob.type });
const uploadRequest = await this.CMAPIService.FileContent({length, path:ChucksManager.path, index: initIndex, blobFile}) const uploadRequest = await this.CMAPIService.FileContent({ length, path: ChucksManager.path, index: initIndex, blobFile })
if(uploadRequest.isOk()) { if (uploadRequest.isOk()) {
path = uploadRequest.value.data path = uploadRequest.value.data
@@ -1034,7 +1101,7 @@ class UploadFileUseCase {
for (let index = indexContinuation; index <= ChucksManager.chunks.totalChunks; index++) { for (let index = indexContinuation; index <= ChucksManager.chunks.totalChunks; index++) {
const uploadRequest = await readAndUploadChunk(index) const uploadRequest = await readAndUploadChunk(index)
if(uploadRequest.isErr()) { if (uploadRequest.isErr()) {
return err(ChucksManager) return err(ChucksManager)
} else { } else {
ChucksManager.setResponse(index, uploadRequest.value as any) ChucksManager.setResponse(index, uploadRequest.value as any)
@@ -1052,9 +1119,9 @@ class PublicationAttachmentEntity {
OriginalFileName: string OriginalFileName: string
blobFile: File blobFile: File
toUpload = false; toUpload = false;
chucksManager : ChucksManager chucksManager: ChucksManager
constructor({base64, extension, blobFile = null, OriginalFileName = null, FileType}) { constructor({ base64, extension, blobFile = null, OriginalFileName = null, FileType }) {
this.FileBase64 = base64; this.FileBase64 = base64;
this.FileExtension = extension; this.FileExtension = extension;
this.blobFile = blobFile this.blobFile = blobFile
@@ -1065,12 +1132,12 @@ class PublicationAttachmentEntity {
} }
fixFileBase64() { fixFileBase64() {
if(this.FileType == 'image' ) { if (this.FileType == 'image') {
if(!this.FileBase64.startsWith('data:')) { if (!this.FileBase64.startsWith('data:')) {
this.FileBase64 = 'data:image/jpg;base64,' + this.FileBase64 this.FileBase64 = 'data:image/jpg;base64,' + this.FileBase64
} }
} else if (this.FileType == 'video' ) { } else if (this.FileType == 'video') {
if(!this.FileBase64.startsWith('data:') && !this.FileBase64.startsWith('http')) { if (!this.FileBase64.startsWith('data:') && !this.FileBase64.startsWith('http')) {
this.FileBase64 = 'data:video/mp4;base64,' + this.FileBase64 this.FileBase64 = 'data:video/mp4;base64,' + this.FileBase64
} }
@@ -1081,8 +1148,8 @@ class PublicationAttachmentEntity {
this.toUpload = true this.toUpload = true
} }
setChunkManger (chunks: Chunks) { setChunkManger(chunks: Chunks) {
this.chucksManager = new ChucksManager({chunks}) this.chucksManager = new ChucksManager({ chunks })
} }
get hasChunkManager() { get hasChunkManager() {
@@ -1090,7 +1157,7 @@ class PublicationAttachmentEntity {
} }
} }
interface IPublicationFormModelEntity { interface IPublicationFormModelEntity {
DateIndex: any DateIndex: any
DocumentId: any DocumentId: any
ProcessId: any ProcessId: any
@@ -1101,7 +1168,7 @@ interface IPublicationFormModelEntity {
} }
class PublicationFormModel implements IPublicationFormModelEntity { class PublicationFormModel implements IPublicationFormModelEntity {
constructor() {} constructor() { }
DateIndex: any; DateIndex: any;
DocumentId: any; DocumentId: any;
ProcessId: any; ProcessId: any;
@@ -1126,18 +1193,18 @@ class PublicationFormMV {
} }
private getVideoFiles() { private getVideoFiles() {
return this.form.Files.filter( x => x.FileType == 'video') return this.form.Files.filter(x => x.FileType == 'video')
} }
private async upload(PublicationAttachmentEntity: PublicationAttachmentEntity) { private async upload(PublicationAttachmentEntity: PublicationAttachmentEntity) {
const fileBlob = PublicationAttachmentEntity.blobFile; const fileBlob = PublicationAttachmentEntity.blobFile;
const fileChunks = new Chunks({chunkSize: 100 }) const fileChunks = new Chunks({ chunkSize: 100 })
fileChunks.setFile(fileBlob) fileChunks.setFile(fileBlob)
PublicationAttachmentEntity.setChunkManger(fileChunks) PublicationAttachmentEntity.setChunkManger(fileChunks)
const ChucksManagers = new ChucksManager({chunks: fileChunks}) const ChucksManagers = new ChucksManager({ chunks: fileChunks })
this.UploadFileUseCase.execute(ChucksManagers) this.UploadFileUseCase.execute(ChucksManagers)
} }
@@ -1146,9 +1213,9 @@ class PublicationFormMV {
const videosFiles = this.getVideoFiles() const videosFiles = this.getVideoFiles()
const videosFilesToUploads = videosFiles.filter( e => e.toUpload == true) const videosFilesToUploads = videosFiles.filter(e => e.toUpload == true)
for(const file of videosFilesToUploads) { for (const file of videosFilesToUploads) {
this.upload(file) this.upload(file)
} }
} }
@@ -1161,17 +1228,17 @@ class Chunks {
chunkSize: number chunkSize: number
private file: File private file: File
constructor({chunkSize}) { constructor({ chunkSize }) {
this.chunkSize = chunkSize * 1024 this.chunkSize = chunkSize * 1024
} }
get totalChunks () { get totalChunks() {
return Math.ceil(this.file.size / this.chunkSize); return Math.ceil(this.file.size / this.chunkSize);
} }
// Function to read a chunk of the file // Function to read a chunk of the file
readChunk(start: number, end: number): Promise<ArrayBuffer> { readChunk(start: number, end: number): Promise<ArrayBuffer> {
const file = this.file const file = this.file
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const reader = new FileReader(); const reader = new FileReader();
@@ -1193,7 +1260,7 @@ class Chunks {
async getChunks(i: number) { async getChunks(i: number) {
i-- i--
if(i < this.totalChunks) { if (i < this.totalChunks) {
const start = i * this.chunkSize; const start = i * this.chunkSize;
const end = Math.min(start + this.chunkSize, this.file.size); const end = Math.min(start + this.chunkSize, this.file.size);
const chunk = await this.readChunk(start, end); const chunk = await this.readChunk(start, end);
@@ -1211,7 +1278,7 @@ interface IUploadResponse {
class ChucksManager { class ChucksManager {
chunks: Chunks chunks: Chunks
uploads: {[key: string]: IUploadResponse } = {} uploads: { [key: string]: IUploadResponse } = {}
path: string = undefined path: string = undefined
get uploadsCount() { get uploadsCount() {
@@ -1219,7 +1286,7 @@ class ChucksManager {
} }
uploadFunc: Function uploadFunc: Function
constructor({chunks}) { constructor({ chunks }) {
this.chunks = chunks this.chunks = chunks
} }
@@ -1234,4 +1301,7 @@ class ChucksManager {
setResponse(index, UploadResponse) { setResponse(index, UploadResponse) {
this.uploads[index] = UploadResponse this.uploads[index] = UploadResponse
} }
} }
+1 -1
View File
@@ -4,4 +4,4 @@ import { doneITProd } from './suport/doneIt'
import { DevDev } from './suport/dev' import { DevDev } from './suport/dev'
export const environment: Environment = DevDev; export const environment: Environment = oaprProd;