Merge branch 'feature/shared-content' of bitbucket.org:equilibriumito/gabinete-digital-fo into feature/shared-content

This commit is contained in:
Peter Maquiran
2023-12-07 16:00:17 +01:00
9 changed files with 573 additions and 72 deletions
+6 -3
View File
@@ -8,6 +8,7 @@ import {
HTTP_INTERCEPTORS, HTTP_INTERCEPTORS,
HttpClient, HttpClient,
} from "@angular/common/http"; } from "@angular/common/http";
import { AuthService } from '../services/auth.service';
import { Observable, throwError, BehaviorSubject, of } from "rxjs"; import { Observable, throwError, BehaviorSubject, of } from "rxjs";
import { catchError, filter, take, switchMap, tap } from "rxjs/operators"; import { catchError, filter, take, switchMap, tap } from "rxjs/operators";
import { SessionStore } from '../store/session.service'; import { SessionStore } from '../store/session.service';
@@ -59,8 +60,8 @@ export class TokenInterceptor implements HttpInterceptor {
return this.refreshToken().pipe( return this.refreshToken().pipe(
switchMap((token: any) => { switchMap((token: any) => {
this.isRefreshing = false; this.isRefreshing = false;
this.refreshTokenSubject.next(token['result'].accessToken); this.refreshTokenSubject.next(token.Authorization);
return next.handle(this.addToken(request, token['result'].accessToken)); return next.handle(this.addToken(request, token.Authorization));
}) })
); );
} else { } else {
@@ -87,9 +88,11 @@ export class TokenInterceptor implements HttpInterceptor {
console.log(tokens) console.log(tokens)
SessionStore.user.Authorization = tokens.Authorization; SessionStore.user.Authorization = tokens.Authorization;
SessionStore.user.RefreshToken = tokens.refreshToken; SessionStore.user.RefreshToken = tokens.refreshToken;
SessionStore.save();
}), }),
catchError((error) => { catchError((error) => {
console.log(error)
SessionStore.user.Authorization = ""; SessionStore.user.Authorization = "";
SessionStore.user.RefreshToken = ""; SessionStore.user.RefreshToken = "";
SessionStore.setInativity(false) SessionStore.setInativity(false)
@@ -113,4 +116,4 @@ export const tokenInterceptor = {
provide: HTTP_INTERCEPTORS, provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor, useClass: TokenInterceptor,
multi: true multi: true
}; };
@@ -115,6 +115,7 @@ export class NewPublicationPage implements OnInit {
seletedContent: any[] = [] seletedContent: any[] = []
// Set a limit for the number of images to display // Set a limit for the number of images to display
displayLimit = 4; displayLimit = 4;
filesSizeSum = 0;
constructor( constructor(
private modalController: ModalController, private modalController: ModalController,
@@ -179,26 +180,33 @@ export class NewPublicationPage implements OnInit {
console.log(capturedImage) console.log(capturedImage)
this.capturedImage = 'data:image/jpeg;base64,' + capturedImage.base64String; this.capturedImage = 'data:image/jpeg;base64,' + capturedImage.base64String;
this.capturedImageTitle = 'foto'; this.capturedImageTitle = 'foto';
if (this.fileSizeToMB(capturedImage.base64String.length) <= 20) {
const compressedImage = await this.compressImageBase64( const compressedImage = await this.compressImageBase64(
this.capturedImage, this.capturedImage,
800, // maxWidth 800, // maxWidth
800, // maxHeight 800, // maxHeight
0.9 // quality 0.9 // quality
).then((picture) => { ).then((picture) => {
console.log('take picture', this.removeTextBeforeSlash(picture, ','),) console.log('take picture', this.removeTextBeforeSlash(picture, ','),)
this.filecontent = true; this.filecontent = true;
this.photoOrVideo = false; this.photoOrVideo = false;
let fileObject = { let fileObject = {
FileBase64: this.removeTextBeforeSlash(picture, ','), FileBase64: this.removeTextBeforeSlash(picture, ','),
FileExtension: capturedImage.format FileExtension: capturedImage.format
} }
this.seletedContent.push(fileObject) this.seletedContent.push(fileObject)
}); });
} else {
if (this.seletedContent.length === 0)
this.filesSizeSum = 0
this.httpErrorHandle.validationMessagge('filessize');
}
} }
async laodPicture() { async laodPicture() {
@@ -230,24 +238,32 @@ export class NewPublicationPage implements OnInit {
this.video = data[0]; this.video = data[0];
console.log(data) console.log(data)
data.forEach(async element => { 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 })
const savedFile = await Filesystem.copy({ .then(async (content) => {
from: element.fullPath, // directory prop removed, Capacitor parses filename for us this.filecontent = true;
to: "video.mp4", let fileObject = {
toDirectory: FilesystemDirectory.Data FileBase64: content.data,
}); FileExtension: 'mp4'
console.log(savedFile.uri) }
Filesystem.readFile({ path: savedFile.uri }) this.seletedContent.push(fileObject)
})
.catch((err) => console.error(err));
} else {
if (this.seletedContent.length === 0)
this.filesSizeSum = 0
this.httpErrorHandle.validationMessagge('filessize')
}
.then(async (content) => {
this.filecontent = true;
let fileObject = {
FileBase64: content.data,
FileExtension: 'mp4'
}
this.seletedContent.push(fileObject)
})
.catch((err) => console.error(err));
}); });
} catch (error) { } catch (error) {
console.log('record video error: ', error) console.log('record video error: ', error)
@@ -262,23 +278,30 @@ export class NewPublicationPage implements OnInit {
}); });
result.files.forEach(element => { result.files.forEach(element => {
if (this.checkFileType.checkFileType(element.mimeType) == 'image' || this.checkFileType.checkFileType(element.mimeType) == 'video') { this.filesSizeSum = this.filesSizeSum + element.size
let resultUrl = decodeURIComponent(element.path); if (this.fileSizeToMB(this.filesSizeSum) <= 20) {
Filesystem.readFile({ path: resultUrl }) if (this.checkFileType.checkFileType(element.mimeType) == 'image' || this.checkFileType.checkFileType(element.mimeType) == 'video') {
let resultUrl = decodeURIComponent(element.path);
Filesystem.readFile({ path: resultUrl })
.then(async (content) => { .then(async (content) => {
console.log(result) console.log(result)
console.log(content) console.log(content)
this.filecontent = true; this.filecontent = true;
let fileObject = { let fileObject = {
FileBase64: content.data, FileBase64: content.data,
FileExtension: this.removeTextBeforeSlash(element.mimeType, '/') FileExtension: this.removeTextBeforeSlash(element.mimeType, '/')
} }
this.seletedContent.push(fileObject) this.seletedContent.push(fileObject)
}) })
.catch((err) => console.error(err)); .catch((err) => console.error(err));
}
} else {
if (this.seletedContent.length === 0)
this.filesSizeSum = 0
this.httpErrorHandle.validationMessagge('filessize')
} }
}); });
}; };
@@ -674,14 +697,16 @@ export class NewPublicationPage implements OnInit {
type: this.intent.type, type: this.intent.type,
url: this.intent.url url: this.intent.url
} }
filesArray = this.intent?.additionalItems; if(this.intent?.additionalItems) {
filesArray = this.intent?.additionalItems;
}
filesArray.push(fistFile) filesArray.push(fistFile)
filesArray.forEach(element => { filesArray.forEach(element => {
let FileExtension = this.removeTextBeforeSlash(element.title, '.') let FileExtension = this.removeTextBeforeSlash(element.title, '.')
if (this.checkFileType.checkFileType(FileExtension) == 'image' || this.checkFileType.checkFileType(FileExtension) == 'video') { if (this.checkFileType.checkFileType(FileExtension) == 'image' || this.checkFileType.checkFileType(FileExtension) == 'video') {
let resultUrl = decodeURIComponent(element.url); let resultUrl = decodeURIComponent(element.url);
Filesystem.readFile({ path: resultUrl }).then(async (content) => { Filesystem.readFile({ path: resultUrl }).then(async (content) => {
console.log('shared base',content.data) console.log('shared base', content.data)
let fileObject = { let fileObject = {
FileBase64: this.removeTextBeforeSlash(content.data, ','), FileBase64: this.removeTextBeforeSlash(content.data, ','),
FileExtension: FileExtension FileExtension: FileExtension
@@ -696,5 +721,12 @@ export class NewPublicationPage implements OnInit {
} }
fileSizeToMB(sizeInBytes) {
var sizeInMB = (sizeInBytes / (1024 * 1024)).toFixed(2);
console.log(sizeInMB + 'MB');
return parseInt(sizeInMB)
}
} }
+11 -3
View File
@@ -4,7 +4,7 @@ import { HttpClient, HttpHeaders, HttpEventType } from '@angular/common/http';
import { LoginUserRespose, UserForm, UserSession } from '../models/user.model'; import { LoginUserRespose, UserForm, UserSession } from '../models/user.model';
import { environment } from 'src/environments/environment'; import { environment } from 'src/environments/environment';
import { BehaviorSubject, of } from 'rxjs'; import { BehaviorSubject, of } from 'rxjs';
import { AlertController } from '@ionic/angular'; import { AlertController, Platform } from '@ionic/angular';
import { SessionStore } from '../store/session.service'; import { SessionStore } from '../store/session.service';
import { AESEncrypt } from '../services/aesencrypt.service'; import { AESEncrypt } from '../services/aesencrypt.service';
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service';
@@ -50,7 +50,8 @@ export class AuthService {
public p: PermissionService, public p: PermissionService,
public ChatSystemService: ChatSystemService, public ChatSystemService: ChatSystemService,
private httpErroHandle: HttpErrorHandle, private httpErroHandle: HttpErrorHandle,
private errorHandler: ErrorHandler) { private errorHandler: ErrorHandler,
private platform: Platform,) {
if (SessionStore.exist) { if (SessionStore.exist) {
if (this.p.userPermission(this.p.permissionList.Chat.access) == true) { if (this.p.userPermission(this.p.permissionList.Chat.access) == true) {
@@ -90,9 +91,16 @@ export class AuthService {
"Content-Type": "application/json", "Content-Type": "application/json",
"Accept": "application/json", "Accept": "application/json",
} }
let channelId;
if ( this.platform.is('desktop') || this.platform.is("mobileweb")){
channelId = 2
} else {
channelId = 1
}
let body = { let body = {
"Auth": user.BasicAuthKey, "Auth": user.BasicAuthKey,
"ChannelId": 1 "ChannelId": channelId
} }
let response: any; let response: any;
+9 -6
View File
@@ -370,7 +370,7 @@ export class ChatService {
async refreshtoken() { async refreshtoken() {
if(this.headers && SessionStore.user.ChatData) { /* if(this.headers && SessionStore.user.ChatData) {
this.headers = this.headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); this.headers = this.headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization);
let options = { let options = {
headers: this.headers headers: this.headers
@@ -406,10 +406,13 @@ export class ChatService {
}) })
} else { } else {
setTimeout(async () => { if(SessionStore.user.Authorization != '') {
this.resetTimer(); setTimeout(async () => {
await this.refreshtoken(); this.resetTimer();
}, 60000) await this.refreshtoken();
}, 60000)
}
} }
@@ -420,7 +423,7 @@ export class ChatService {
} else if (!this.headers) { } else if (!this.headers) {
this.setheader() this.setheader()
this.refreshtoken() this.refreshtoken()
} } */
} }
@@ -96,6 +96,9 @@ export class HttpErrorHandle {
case 'filetype': case 'filetype':
this.toastService._badRequest('Formato de ficheiro inválido!') this.toastService._badRequest('Formato de ficheiro inválido!')
break; break;
case 'filessize':
this.toastService._badRequest('Excedeu o limite de 20 MB!')
break;
default: default:
this.toastService._badRequest('') this.toastService._badRequest('')
@@ -0,0 +1,124 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Filesystem, FilesystemDirectory } from '@capacitor/filesystem';
import { Platform } from '@ionic/angular';
declare var FFmpeg: any;
@Injectable({
providedIn: 'root'
})
export class VideoCompressionService {
constructor(
private http: HttpClient,
private platform: Platform
) { }
async compressVideo(inputFile: string, outputFileName: string, quality: string = 'medium'): Promise<void> {
// Load FFmpeg
await this.loadFFmpeg();
// Input file
const inputBuffer = await this.fetchVideo(inputFile);
// Output file path
const outputPath = await this.getOutputFilePath(outputFileName);
// Run FFmpeg command
await this.runFFmpegCommand(inputBuffer, outputPath, quality);
console.log('Video compression complete!');
}
private async loadFFmpeg(): Promise<void> {
if (!FFmpeg.isLoaded()) {
await FFmpeg.load();
}
}
private async fetchVideo(url: string): Promise<ArrayBuffer> {
const response = await this.http.get(url, { responseType: 'arraybuffer' }).toPromise();
return response;
}
private async getOutputFilePath(outputFileName: string): Promise<string> {
const dataDirectory = await Filesystem.getUri({
directory: FilesystemDirectory.Data,
path: ''
});
return `${dataDirectory.uri}/${outputFileName}`;
}
private async runFFmpegCommand(inputBuffer: ArrayBuffer, outputPath: string, quality: string): Promise<void> {
await FFmpeg.run('-i', inputBuffer, '-c:v', 'libx264', '-preset', quality, outputPath);
}
}
//Mobile
/* import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
import { Filesystem, FilesystemDirectory, FilesystemEncoding } from '@capacitor/filesystem';
import { Platform } from '@ionic/angular';
declare var FFmpeg: any;
@Injectable({
providedIn: 'root'
})
export class VideoCompressionService {
constructor(
private http: HTTP,
private platform: Platform
) { }
async compressVideo(inputFile: string, outputFileName: string, quality: string = 'medium'): Promise<void> {
// Load FFmpeg
await this.loadFFmpeg();
// Input file
const inputBuffer = await this.fetchVideo(inputFile);
// Output file path
const outputPath = await this.getOutputFilePath(outputFileName);
// Run FFmpeg command
await this.runFFmpegCommand(inputBuffer, outputPath, quality);
console.log('Video compression complete!');
}
private async loadFFmpeg(): Promise<void> {
if (!FFmpeg.isLoaded()) {
await FFmpeg.load();
}
}
private async fetchVideo(url: string): Promise<ArrayBuffer> {
const response = await this.http.sendRequest(url, {
method: 'get',
responseType: 'arraybuffer'
});
return response.data;
}
private async getOutputFilePath(outputFileName: string): Promise<string> {
const dataDirectory = await Filesystem.getUri({
directory: FilesystemDirectory.Data,
path: ''
});
return `${dataDirectory.uri}/${outputFileName}`;
}
private async runFFmpegCommand(inputBuffer: ArrayBuffer, outputPath: string, quality: string): Promise<void> {
await FFmpeg.run('-i', inputBuffer, '-c:v', 'libx264', '-preset', quality, outputPath);
}
}
*/
@@ -159,6 +159,7 @@ export class NewEventPage implements OnInit {
ngOnInit() { ngOnInit() {
console.log(' INTERVENIENTES',this.taskParticipants)
this.changeProfileService.registerCallback(() => { this.changeProfileService.registerCallback(() => {
this.initializeData() this.initializeData()
}) })
@@ -1009,7 +1010,7 @@ export class NewEventPage implements OnInit {
} }
async fetchContacts(filter: string) { async fetchContacts(filter: string) {
console.log(this.loggeduser.Profile)
if (this.loggeduser.Profile == 'PR') { if (this.loggeduser.Profile == 'PR') {
this.contactsService.getContacts(filter).subscribe(result => { this.contactsService.getContacts(filter).subscribe(result => {
if (this.eventPersons != null) { if (this.eventPersons != null) {
@@ -53,6 +53,7 @@ export class NewPublicationPage implements OnInit {
captureContent: any; captureContent: any;
seletedContent: any[] = [] seletedContent: any[] = []
displayLimit = 4; displayLimit = 4;
filesSizeSum = 0;
constructor( constructor(
public photoService: PhotoService, public photoService: PhotoService,
@@ -156,7 +157,7 @@ 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','/')
} }
this.seletedContent.push(fileObject) this.seletedContent.push(fileObject)
}); });
@@ -185,7 +186,7 @@ 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','/')
} }
this.seletedContent.push(fileObject) this.seletedContent.push(fileObject)
}); });
@@ -198,18 +199,28 @@ export class NewPublicationPage implements OnInit {
({ ({
multiple: true, multiple: true,
}); });
result.files.forEach(async element => { result.files.forEach(async element => {
console.log(element)
if(this.checkFileType.checkFileType(element.mimeType) == 'image' || this.checkFileType.checkFileType(element.mimeType) == 'video') { if(this.checkFileType.checkFileType(element.mimeType) == 'image' || this.checkFileType.checkFileType(element.mimeType) == 'video') {
this.convertBlobToBase64(element.blob).then((value) => { this.convertBlobToBase64(element.blob).then((value) => {
this.filesSizeSum = this.filesSizeSum + element.size
console.log(element.mimeType) if(this.fileSizeToMB(this.filesSizeSum) <= 20) {
let fileObject = { let fileObject = {
FileBase64: value, FileBase64: value,
FileExtension: this.removeTextBeforeSlash(element.mimeType) FileExtension: this.removeTextBeforeSlash(element.mimeType,'/')
} }
this.seletedContent.push(fileObject) this.seletedContent.push(fileObject)
this.filecontent = true; this.filecontent = true;
} else {
if(this.seletedContent.length === 0)
this.filesSizeSum = 0
this.httpErroHandle.validationMessagge('filessize');
}
}) })
} else { } else {
this.httpErroHandle.validationMessagge('filetype'); this.httpErroHandle.validationMessagge('filetype');
@@ -471,14 +482,330 @@ export class NewPublicationPage implements OnInit {
}) })
} }
removeTextBeforeSlash(inputString) { removeTextBeforeSlash(inputString,mark) {
if (inputString.includes('/')) { if (inputString.includes(mark)) {
const parts = inputString.split('/'); const parts = inputString.split(mark);
return parts.length > 1 ? parts[1] : inputString; return parts.length > 1 ? parts[1] : inputString;
} else { } else {
return inputString; 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)
}
} }
File diff suppressed because one or more lines are too long