fix message and and updload

This commit is contained in:
Peter Maquiran
2024-04-01 15:59:18 +01:00
parent 28beeb3879
commit f754da8cde
5 changed files with 24 additions and 181 deletions
@@ -376,8 +376,11 @@ export class NewPublicationPage implements OnInit {
if (!window["sharedContent"]) { if (!window["sharedContent"]) {
this.close(); this.close();
} else {
alert('dont close')
} }
this.PublicationFromMvService.publicationType = this.publicationType as any
this.PublicationFromMvService.setFolderId(this.folderId) this.PublicationFromMvService.setFolderId(this.folderId)
await this.PublicationFromMvService.save() await this.PublicationFromMvService.save()
@@ -394,6 +397,7 @@ export class NewPublicationPage implements OnInit {
close() { close() {
alert('close');
this.modalController.dismiss(this.PublicationFromMvService.form).then(() => { this.modalController.dismiss(this.PublicationFromMvService.form).then(() => {
this.showLoader = true; this.showLoader = true;
}); });
@@ -1,5 +1,4 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { PublicationFormMV } from 'src/app/shared/publication/upload/upload-streaming.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -151,6 +151,7 @@ class ReconnectingWebSocketSignalR {
console.log('committing') console.log('committing')
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if(this.isOpen) { if(this.isOpen) {
console.log('open')
try { try {
console.log('this.connection.invoke', this.connection) console.log('this.connection.invoke', this.connection)
this.connection.invoke("CommitUpload", path).then((e) => { this.connection.invoke("CommitUpload", path).then((e) => {
@@ -168,6 +169,7 @@ class ReconnectingWebSocketSignalR {
} }
} else { } else {
console.log('wait')
this.onConnect.push(()=> { this.onConnect.push(()=> {
resolve(this.commit(path)) resolve(this.commit(path))
}) })
@@ -78,6 +78,8 @@ export class PublicationFromMvService {
this.form.send = true this.form.send = true
const upload = await this.uploadVideosFiles() const upload = await this.uploadVideosFiles()
console.log('release chunks')
const needChunk = this.needToUploadChunk() const needChunk = this.needToUploadChunk()
if(needChunk.length == 0 ) { if(needChunk.length == 0 ) {
@@ -120,7 +122,6 @@ export class PublicationFromMvService {
this.httpErroHandle.httpStatusHandle(error) this.httpErroHandle.httpStatusHandle(error)
if (error.status == 404) { if (error.status == 404) {
this.PublicationFolderService.deletePost(this.form.ProcessId, this.form.DocumentId) this.PublicationFolderService.deletePost(this.form.ProcessId, this.form.DocumentId)
// this.goBack();
} else { } else {
window['upload-header-set-retry'](this.id) window['upload-header-set-retry'](this.id)
} }
@@ -130,7 +131,6 @@ export class PublicationFromMvService {
} else { } else {
window['upload-header-set-retry'](this.id)
this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo") this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo")
} }
@@ -152,6 +152,8 @@ export class PublicationFromMvService {
window['upload-header-set-percentage'](this.id, 100) window['upload-header-set-percentage'](this.id, 100)
} }
console.log('release chunk')
if(upload) { if(upload) {
this.form.Files = this.form.Files.map((e:PublicationAttachmentEntity) => { this.form.Files = this.form.Files.map((e:PublicationAttachmentEntity) => {
if(e.FileType == 'video' && e.toUpload) { if(e.FileType == 'video' && e.toUpload) {
@@ -167,6 +169,12 @@ export class PublicationFromMvService {
return e return e
}) })
} else {
window['upload-header-set-retry'](this.id)
this.toastService._badRequest("ocorreu um erro ao enviar o ficheiro")
return true
// loader.remove()
}
@@ -181,14 +189,12 @@ export class PublicationFromMvService {
publication.DocumentId = null; publication.DocumentId = null;
publication.ProcessId = this.folderId publication.ProcessId = this.folderId
try { try {
await this.publications.CreatePublication(publication.ProcessId, publication).toPromise() await this.publications.CreatePublication(publication.ProcessId, publication).toPromise()
this.closeApp()
if (this.publicationType == '1') {
if (this.publicationType == '1') {
this.httpErroHandle.httpsSucessMessagge('Criar publicação')
} else if (this.publicationType == '2') { } else if (this.publicationType == '2') {
this.httpErroHandle.httpsSucessMessagge('Criar publicação') this.httpErroHandle.httpsSucessMessagge('Criar publicação')
} else if (this.publicationType == '3') { } else if (this.publicationType == '3') {
@@ -197,6 +203,7 @@ export class PublicationFromMvService {
// this.goBackToViewPublications.emit(); // this.goBackToViewPublications.emit();
window['upload-header-set-remove'](this.id); window['upload-header-set-remove'](this.id);
this.closeApp()
this.publicationFolderService.getPublicationsIds(this.folderId) this.publicationFolderService.getPublicationsIds(this.folderId)
} catch (error) { } catch (error) {
window['upload-header-set-retry'](this.id) window['upload-header-set-retry'](this.id)
@@ -205,14 +212,6 @@ export class PublicationFromMvService {
// loader.remove() // loader.remove()
} }
} else {
window['upload-header-set-retry'](this.id)
this.toastService._badRequest("ocorreu um erro ao enviar o ficheiro")
// loader.remove()
}
} else { } else {
this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo") this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo")
@@ -230,6 +229,7 @@ export class PublicationFromMvService {
closeApp() { closeApp() {
if (window["sharedContent"]) { if (window["sharedContent"]) {
alert('close android')
if (this.platform.is('android')) { if (this.platform.is('android')) {
App.exitApp() App.exitApp()
@@ -275,7 +275,7 @@ export class PublicationFromMvService {
if(PublicationAttachmentEntity.hasBlob) { if(PublicationAttachmentEntity.hasBlob) {
const fileBlob = PublicationAttachmentEntity.blobFile; const fileBlob = PublicationAttachmentEntity.blobFile;
const fileChunks = new Chunks({chunkSize: 1000 }) const fileChunks = new Chunks({chunkSize: 50 })
fileChunks.setFile(fileBlob) fileChunks.setFile(fileBlob)
PublicationAttachmentEntity.setChunkManger(fileChunks) PublicationAttachmentEntity.setChunkManger(fileChunks)
} else { } else {
@@ -322,6 +322,7 @@ export class PublicationFromMvService {
} else { } else {
console.log('already uploading') console.log('already uploading')
resolve(true)
} }
}) })
@@ -347,6 +348,8 @@ export class PublicationFromMvService {
Promises.push(promise) Promises.push(promise)
} }
console.log('Promises', Promises)
// Use Promise.all to wait for all promises to resolve // Use Promise.all to wait for all promises to resolve
Promise.all(Promises) Promise.all(Promises)
.then((results) => { .then((results) => {
@@ -227,171 +227,6 @@ export class PublicationFormModel implements IPublicationFormModelEntity {
} }
} }
export class PublicationFormMV {
readonly id = uuidv4()
private UploadFileUseCase = new UploadFileUseCase()
form = new PublicationFormModel()
ObjectMergeNotification = new ObjectMergeNotification()
totalPercentage = 0
constructor() {
this.ObjectMergeNotification.connect();
window['upload-header-set-add'](this.id, this.totalPercentage)
}
setDataToFrom(data: IPublicationFormModelEntity) {
this.form.setData(data)
}
private getVideoFiles() {
return this.form.Files.filter( x => x.FileType == 'video')
}
async commit(PublicationAttachmentEntity: PublicationAttachmentEntity) {
PublicationAttachmentEntity.chucksManager.doneChunkUpload()
const mergeRequest = await this.ObjectMergeNotification.socket.commit(PublicationAttachmentEntity.chucksManager.path)
if(mergeRequest.isOk()) {
console.log("commit")
PublicationAttachmentEntity.chucksManager.contentSetReady()
return true
} else {
console.log('no commit')
return false
}
}
private upload(PublicationAttachmentEntity: PublicationAttachmentEntity) {
return new Promise(async (resolve, reject)=> {
if(!PublicationAttachmentEntity.hasChunkManger) {
if(PublicationAttachmentEntity.hasBlob) {
const fileBlob = PublicationAttachmentEntity.blobFile;
const fileChunks = new Chunks({chunkSize: 50 })
fileChunks.setFile(fileBlob)
PublicationAttachmentEntity.setChunkManger(fileChunks)
} else {
const Base64 = PublicationAttachmentEntity.Base64;
const fileChunks = new ChunksBase64({chunkSize: 50 })
fileChunks.setFile(Base64)
PublicationAttachmentEntity.setChunkManger(fileChunks)
}
PublicationAttachmentEntity.chucksManager.updateTotalPercentageTrigger = () => {
this.uploadPercentage()
}
}
let attemp = 0;
let result: Result<true, IOUploadError>
if( PublicationAttachmentEntity.chucksManager.isUploading == false && PublicationAttachmentEntity.chucksManager.doneUpload == false) {
do {
attemp++
PublicationAttachmentEntity.chucksManager.clearManualRetry()
PublicationAttachmentEntity.chucksManager.setUploading()
result = await this.UploadFileUseCase.execute(PublicationAttachmentEntity)
PublicationAttachmentEntity.chucksManager.clearUploading()
} while (attemp<3 && result.isErr() && result.error == 'slow')
if(result.isErr()) {
PublicationAttachmentEntity.chucksManager.setManualRetry()
resolve(false)
} else {
return await resolve(this.commit(PublicationAttachmentEntity))
}
} else if ( PublicationAttachmentEntity.chucksManager.contentReady == false) {
console.log("try to send again")
return await resolve(this.commit(PublicationAttachmentEntity))
} else {
console.log('already uploading')
}
})
}
uploadVideosFiles(): Promise<Boolean> {
return new Promise((resolve, reject) => {
// this.ObjectMergeNotification.socket.registerWhenConnected(() => {
const videosFiles = this.getVideoFiles()
window['upload-header-set-percentage'](this.id, 1)
const videosFilesToUploads = videosFiles.filter( e => e.FileType == "video" && e.toUpload && e.blobFile)
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.');
window['upload-header-set-remove'](this.id);
resolve(true)
} else {
window['upload-header-set-remove'](this.id);
resolve(false)
console.log('Some promises failed to resolve successfully.');
}
})
.catch((error) => {
resolve(false)
console.error('An error occurred while resolving promises:', error);
});
//})
})
}
uploadPercentage() {
const videosFiles = this.getVideoFiles()
const percentageArray = videosFiles.map((e) => e.chucksManager.calculatePercentage())
// Check if the array is not empty
if (percentageArray.length === 0) {
window['upload-header-set-percentage'](this.id, this.totalPercentage)
return 0;
} else {
let sum = percentageArray.reduce((acc, percentage) => acc + percentage, 0);
// Calculate the average percentage
let averagePercentage = sum / percentageArray.length;
this.totalPercentage = averagePercentage
window['upload-header-set-percentage'](this.id, this.totalPercentage)
return averagePercentage;
}
}
}
export class Chunks { export class Chunks {