From ca0b968abe00cec26e8d64f63e55d392f25a4907 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Tue, 26 Mar 2024 12:03:30 +0100 Subject: [PATCH] fix --- src/app/interceptors/chatToken.interceptor.ts | 3 - src/app/pages/chat/chat.page.ts | 13 +- .../group-messages/group-messages.page.ts | 14 +- src/app/pages/chat/messages/messages.page.ts | 13 +- src/app/pages/events/events.page.html | 2 - .../expediente-detail.page.ts | 2 + .../new-publication/new-publication.module.ts | 4 + .../new-publication/new-publication.page.html | 87 +--- .../new-publication/new-publication.page.ts | 471 +++++++----------- .../view-publications.page.ts | 37 +- src/app/services/chat/chat-system.service.ts | 9 - src/app/services/chat/room.service.ts | 7 - src/app/services/notifications.service.ts | 12 - .../publication/holder.service.spec.ts | 16 + .../publication/holder.service.ts} | 2 +- .../publication-holder.service.spec.ts | 16 + .../publication/publication-holder.service.ts | 98 ++++ .../services/socket-connection-mcr.service.ts | 105 ++-- .../group-messages/group-messages.page.ts | 13 +- src/app/shared/chat/messages/messages.page.ts | 12 +- src/app/shared/header/header.page.html | 23 +- src/app/shared/header/header.page.scss | 3 +- src/app/shared/header/header.page.ts | 10 +- .../new-publication/new-publication.page.html | 8 +- .../new-publication/new-publication.page.ts | 191 ++----- ...ts => publication-from-mv.service.spec.ts} | 8 +- .../upload/publication-from-mv.service.ts | 356 +++++++++++++ .../upload/upload-streaming.service.ts | 117 ++++- .../view-publications.page.html | 2 +- .../view-publications.page.ts | 148 ++---- src/environments/environment.prod.ts | 6 +- src/environments/environment.ts | 2 +- 32 files changed, 1016 insertions(+), 794 deletions(-) create mode 100644 src/app/services/publication/holder.service.spec.ts rename src/app/{shared/publication/upload/publication-form-mv.service.ts => services/publication/holder.service.ts} (72%) create mode 100644 src/app/services/publication/publication-holder.service.spec.ts create mode 100644 src/app/services/publication/publication-holder.service.ts rename src/app/shared/publication/upload/{publication-form-mv.service.spec.ts => publication-from-mv.service.spec.ts} (50%) create mode 100644 src/app/shared/publication/upload/publication-from-mv.service.ts diff --git a/src/app/interceptors/chatToken.interceptor.ts b/src/app/interceptors/chatToken.interceptor.ts index 974b7d783..66f27b7e4 100644 --- a/src/app/interceptors/chatToken.interceptor.ts +++ b/src/app/interceptors/chatToken.interceptor.ts @@ -103,9 +103,6 @@ export class ChatTokenInterceptor implements HttpInterceptor { private addToken(request: HttpRequest, token: string) { let headers = new HttpHeaders(); - - console.log('X-User-Id', SessionStore.user.ChatData.data.userId) - console.log('X-Auth-Token', SessionStore.user.ChatData.data.authToken) headers = headers.set('X-User-Id', SessionStore.user.ChatData.data.userId); headers = headers.set('X-Auth-Token', SessionStore.user.ChatData.data.authToken); diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index e0e210b80..a2a7ea13b 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -32,7 +32,6 @@ import { EventTrigger } from 'src/app/services/eventTrigger.service'; import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; import { RouteService } from 'src/app/services/route.service'; import { Plugins } from '@capacitor/core'; -import { ChangeDetectorRef } from '@angular/core'; const { App } = Plugins; @@ -129,8 +128,7 @@ export class ChatPage implements OnInit { private eventTriger: EventTrigger, private RochetChatConnectorService: RochetChatConnectorService, private zone: NgZone, - public RouteService: RouteService, - private ChangeDetectorRef: ChangeDetectorRef + public RouteService: RouteService ) { this.headers = new HttpHeaders();; @@ -178,15 +176,6 @@ export class ChatPage implements OnInit { } }); - this.ChatSystemService.setMainChangeDetector(()=> { - this.changeDetector() - }) - - } - - changeDetector = () => { - console.log('run detection') - this.ChangeDetectorRef.detectChanges() } diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index 2ff2d020b..81d11e024 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -110,7 +110,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { private fileOpener: FileOpener, public RouteService: RouteService, private FileValidatorService: FileValidatorService, - private ChangeDetectorRef: ChangeDetectorRef ) { this.ChatSystemService.getUser() @@ -147,10 +146,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { this.ChatSystemService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked; this.ChatSystemService.openRoom(this.roomId) this.groupNameFormart = this.ChatSystemService.getGroupRoom(this.roomId).name.split('-').join(' ') - - this.ChatSystemService.getGroupRoom(this.roomId).setChangeDetector(()=> { - this.changeDetector() - }) } catch (error) { setTimeout(() => { this.open() @@ -159,11 +154,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { } - changeDetector = () => { - console.log('run detection page') - this.ChangeDetectorRef.detectChanges() - } - ngOnInit() { this.loggedUser = this.loggedUserChat; @@ -841,7 +831,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { async addFileToChat(types: typeof FileType[]) { - + const roomId = this.roomId @@ -879,7 +869,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { } }) return - + } const file: any = await this.fileService.getFileFromDevice(types); diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 48adbc892..ebad6ad92 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -37,7 +37,6 @@ import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-co import { FileValidatorService } from "src/app/services/file/file-validator.service" import { sanitize } from "sanitize-filename-ts"; import { FilePicker } from '@capawesome/capacitor-file-picker'; -import { ChangeDetectorRef } from '@angular/core'; @@ -125,7 +124,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { private router: Router, public RochetChatConnectorService: RochetChatConnectorService, private FileValidatorService: FileValidatorService, - private ChangeDetectorRef: ChangeDetectorRef ) { try { @@ -144,10 +142,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { this.ChatSystemService.getDmRoom(this.roomId).loadHistory({}) this.ChatSystemService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked this.ChatSystemService.openRoom(this.roomId) - this.ChatSystemService.getDmRoom(this.roomId).setChangeDetector(() => { - - this.changeDetector() - }) setTimeout(() => { this.scrollToBottomClicked() @@ -157,10 +151,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } } - changeDetector = () => { - console.log('run detection page') - this.ChangeDetectorRef.detectChanges() - } + ngOnInit() { try { @@ -1127,7 +1118,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { cssClass: 'modal modal-desktop' }); await modal.present(); -/* +/* var blob = new Blob([pdfString], { type: 'application/pdf' }); console.log('blob blob', blob) diff --git a/src/app/pages/events/events.page.html b/src/app/pages/events/events.page.html index 569c40a82..b8356548b 100644 --- a/src/app/pages/events/events.page.html +++ b/src/app/pages/events/events.page.html @@ -314,5 +314,3 @@ - -Visit W3Schools.com! diff --git a/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts b/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts index b0eb564af..338a21563 100644 --- a/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts +++ b/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts @@ -253,6 +253,8 @@ export class ExpedienteDetailPage implements OnInit { this.TaskService.loadExpedientes(); + console.log("res========", res) + this.task = { "SerialNumber": res.serialNumber, "Folio": res.workflowInstanceDataFields.Subject, diff --git a/src/app/pages/publications/new-publication/new-publication.module.ts b/src/app/pages/publications/new-publication/new-publication.module.ts index aeaa9cc9c..48f26efaa 100644 --- a/src/app/pages/publications/new-publication/new-publication.module.ts +++ b/src/app/pages/publications/new-publication/new-publication.module.ts @@ -9,6 +9,9 @@ import { NewPublicationPageRoutingModule } from './new-publication-routing.modul import { NewPublicationPage } from './new-publication.page'; import '@teamhive/capacitor-video-recorder'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; + + @NgModule({ imports: [ CommonModule, @@ -16,6 +19,7 @@ import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; IonicModule, NewPublicationPageRoutingModule, FontAwesomeModule, + MatProgressBarModule, ], exports: [NewPublicationPage], declarations: [NewPublicationPage] diff --git a/src/app/pages/publications/new-publication/new-publication.page.html b/src/app/pages/publications/new-publication/new-publication.page.html index 9ea946437..a8793f6e5 100644 --- a/src/app/pages/publications/new-publication/new-publication.page.html +++ b/src/app/pages/publications/new-publication/new-publication.page.html @@ -11,7 +11,7 @@
-
@@ -21,41 +21,50 @@
-
-
+
Fotografia Anexada
-
+
X
+
+ + + +
- - + -

mais {{ seletedContent.length - displayLimit }}

+

mais {{ PublicationFromMvService.form.Files.length - displayLimit }}

{{capturedImageTitle}}

@@ -66,22 +75,6 @@
- - -
@@ -111,51 +104,7 @@
- - - -
diff --git a/src/app/pages/publications/new-publication/new-publication.page.ts b/src/app/pages/publications/new-publication/new-publication.page.ts index 230b452ac..a93281620 100644 --- a/src/app/pages/publications/new-publication/new-publication.page.ts +++ b/src/app/pages/publications/new-publication/new-publication.page.ts @@ -27,14 +27,16 @@ import { FilePicker } from '@capawesome/capacitor-file-picker'; import { CapacitorVideoPlayer } from 'capacitor-video-player'; import { CaptureError, CaptureImageOptions, MediaCapture, MediaFile } from '@awesome-cordova-plugins/media-capture/ngx'; import { Capacitor } from '@capacitor/core'; -import { File } from '@ionic-native/file/ngx'; +import { File as IonicFile } from '@ionic-native/file/ngx'; import { Media } from '@ionic-native/media/ngx'; import { checkFileTypeService } from 'src/app/services/checkFileType.service'; import { FileValidatorService } from "src/app/services/file/file-validator.service" import { App } from '@capacitor/app'; import { NavigationExtras, Router } from '@angular/router'; import { VideoconvertService } from 'src/app/services/videoconvert.service' - +import { PublicationAttachmentEntity } from 'src/app/shared/publication/upload/upload-streaming.service'; +import { PublicationFromMvService } from "src/app/shared/publication/upload/publication-from-mv.service" +import { File } from '../../../models/chatMethod'; const config = { quality: 0.5, @@ -88,8 +90,6 @@ export class NewPublicationPage implements OnInit { validateFrom = false showLoader: boolean; - publication: Publication; - pub: Publication = new Publication(); folderId: string; image: Image = new Image(); @@ -117,7 +117,6 @@ export class NewPublicationPage implements OnInit { photoOrVideo: boolean = false; fileType = ""; filecontent: boolean; - seletedContent: any[] = [] // Set a limit for the number of images to display displayLimit = 4; filesSizeSum = 0; @@ -140,22 +139,38 @@ export class NewPublicationPage implements OnInit { public checkFileType: checkFileTypeService, private FileValidatorService: FileValidatorService, private router: Router, - private videoconvertService: VideoconvertService + private videoconvertService: VideoconvertService, + public PublicationFromMvService: PublicationFromMvService, ) { this.publicationType = this.navParams.get('publicationType'); this.folderId = this.navParams.get('folderId'); - this.publication = this.navParams.get('publication'); - if (this.publication) { - this.seletedContent = this.publication.Files; + const publication = this.navParams.get('publication'); + if (publication && typeof publication?.Files == 'object') { this.filecontent = true; + + const newFiles: PublicationAttachmentEntity[] = publication.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) { + this.PublicationFromMvService.form.Files.push(files) + } } - console.log('Edit', this.publication) + + this.publicationTitle = 'Nova Publicação'; this.intent = this.navParams.get('intent'); this.convertBlobToBase64Worker = new Worker(new URL('./convertBlobToBase64.worker.js', import.meta.url)); - + this.PublicationFromMvService.clear() } ngOnInit() { @@ -204,17 +219,22 @@ export class NewPublicationPage implements OnInit { console.log('take picture', this.removeTextBeforeSlash(picture, ','),) this.filecontent = true; this.photoOrVideo = false; - let fileObject = { - FileBase64: this.removeTextBeforeSlash(picture, ','), - FileExtension: capturedImage.format, - OriginalFileName: 'image' - } - this.seletedContent.push(fileObject) + + const newAttachment = new PublicationAttachmentEntity( + { + base64: this.removeTextBeforeSlash(picture, ','), + extension: capturedImage.format, + OriginalFileName: "image", + FileType: 'image' + } + ) + + this.PublicationFromMvService.form.Files.push(newAttachment) }); } else { - if (this.seletedContent.length === 0) + if (this.PublicationFromMvService.form.Files.length === 0) this.filesSizeSum = 0 this.httpErrorHandle.validationMessagge('filessize'); @@ -255,9 +275,9 @@ export class NewPublicationPage implements OnInit { try { if (this.platform.is('ios')) { - this.recordevideoIos(element.fullPath) + this.recordevideoIos(element.fullPath, element) } else { - this.recordVideoAndroid(element.fullPath) + this.recordVideoAndroid(element.fullPath, element) } } catch (e) { @@ -265,7 +285,7 @@ export class NewPublicationPage implements OnInit { } } else { - if (this.seletedContent.length === 0) + if (this.PublicationFromMvService.form.Files.length === 0) this.filesSizeSum = 0 this.httpErrorHandle.validationMessagge('filessize') @@ -277,35 +297,35 @@ export class NewPublicationPage implements OnInit { } } - async loadVideo() { - const result = await FilePicker.pickMedia ({ multiple: true, }); - console.log(result.files) - result.files.forEach(async element => { - this.filesSizeSum = this.filesSizeSum + element.size - if (this.fileSizeToMB(this.filesSizeSum) <= 20) { - console.log('pass size verificartion') + async loadVideo() { + const result = await FilePicker.pickMedia ({ multiple: true, }); + console.log(result.files) + result.files.forEach(async element => { + this.filesSizeSum = this.filesSizeSum + element.size + if (this.fileSizeToMB(this.filesSizeSum) <= 20) { + console.log('pass size verificartion') if (this.checkFileType.checkFileType(element.mimeType) == 'video' && this.platform.is('ios')) { - let resultUrl = decodeURIComponent(element.path); console.log('pass type verification ', resultUrl) - try { - this.recordevideoIos(resultUrl) - } catch (error) { - console.log('upload video error: ', error) - } - } else if (this.checkFileType.checkFileType(element.mimeType) == 'image' || this.checkFileType.checkFileType(element.mimeType) == 'video') { + let resultUrl = decodeURIComponent(element.path); console.log('pass type verification ', resultUrl) + try { + this.recordevideoIos(resultUrl, element) + } catch (error) { + console.log('upload video error: ', error) + } + } else if (this.checkFileType.checkFileType(element.mimeType) == 'image' || this.checkFileType.checkFileType(element.mimeType) == 'video') { let resultUrl = decodeURIComponent(element.path); console.log('pass type verification ', resultUrl) - try { - this.loadVideoAndroid(resultUrl,element) - } catch (error) { - console.log('upload video error: ', error) - } - } - } else { - if (this.seletedContent.length === 0) - this.filesSizeSum = 0 + try { + this.loadVideoAndroid(resultUrl,element) + } catch (error) { + console.log('upload video error: ', error) + } + } + } else { + if (this.PublicationFromMvService.form.Files.length === 0) + this.filesSizeSum = 0 - this.httpErrorHandle.validationMessagge('filessize') - } + this.httpErrorHandle.validationMessagge('filessize') + } }); }; @@ -367,14 +387,14 @@ export class NewPublicationPage implements OnInit { injectValidation() { this.Form = new FormGroup({ - Subject: new FormControl(this.pub.Title, [ + Subject: new FormControl(this.PublicationFromMvService.form.Title, [ Validators.required, // Validators.minLength(4) ]), capturedImage: new FormControl(this.capturedImage, [ ]), - Message: new FormControl(this.pub.Message, [ + Message: new FormControl(this.PublicationFromMvService.form.Message, [ Validators.required, Validators.maxLength(1000) @@ -390,172 +410,26 @@ export class NewPublicationPage implements OnInit { if (this.Form.invalid) return false - if (this.seletedContent.length != 0) { + if (this.PublicationFromMvService.form.Files.length != 0) { - if (this.publicationType == '3') { - const loader = this.toastService.loading() - - // has file - if (this.PublicationFolderService.PublicationHasImage(this.publication)) { - this.publication = { - DateIndex: this.publication.DateIndex, - DocumentId: this.publication.DocumentId, - ProcessId: this.publication.ProcessId, - Title: this.pub.Title, - Message: this.pub.Message, - DatePublication: this.publication.DatePublication, - OriginalFileName: this.publication.OriginalFileName, - Files: this.seletedContent, - } - - /* } else if (this.capturedVideo != '' && this.capturedImage == '') { - this.publication = { - DateIndex: this.publication.DateIndex, - DocumentId: this.publication.DocumentId, - ProcessId: this.publication.ProcessId, - Title: this.pub.Title, - Message: this.pub.Message, - DatePublication: this.publication.DatePublication, - OriginalFileName: this.publication.OriginalFileName || 'video', - Files: this.seletedContent, - FileExtension: 'mp4', - } - } */ - // no names - } else if (!this.PublicationFolderService.PublicationHasImage(this.publication)) { - this.publication = { - DateIndex: this.publication.DateIndex, - DocumentId: this.publication.DocumentId, - ProcessId: this.publication.ProcessId, - Title: this.pub.Title, - Message: this.pub.Message, - DatePublication: this.publication.DatePublication, - OriginalFileName: this.publication.OriginalFileName, - Files: this.seletedContent, - } - - - } /* else { - this.publication = { - DateIndex: this.publication.DateIndex, - DocumentId: this.publication.DocumentId, - ProcessId: this.publication.ProcessId, - Title: this.pub.Title, - Message: this.pub.Message, - DatePublication: this.publication.DatePublication, - OriginalFileName: this.publication.OriginalFileName, - FileBase64: this.publication.FileBase64, - FileExtension: this.publication.FileExtension || 'jpeg', - } - - } */ - - - try { - - const response = await this.publications.UpdatePublication(this.publication.ProcessId, this.publication).toPromise() - - this.httpErrorHandle.httpsSucessMessagge('Editar publicação') - console.log({ response }) - - - this.close(); - } catch (error) { - if (error.status == 404) { - this.PublicationFolderService.deletePost(this.publication.ProcessId, this.publication.DocumentId) - this.close(); - } - this.httpErrorHandle.httpStatusHandle(error) - } finally { - loader.remove() - } - - } - else { - - const date = formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss') - - /* this.seletedContent = this.seletedContent.map((e) => { - if(e.FileExtension == "mp4") { - return { - FileBase64: e.FileBase64, - FileExtension: 'data:video/mp4;base64,'+e.FileExtension, - OriginalFileName: "video", - } - } - - return e - }) */ - - /* if (this.capturedImage != '') { */ - this.publication = { - DateIndex: date, - DocumentId: null, - ProcessId: JSON.stringify(this.folderId), - Title: this.pub.Title, - Message: this.pub.Message, - DatePublication: date, - OriginalFileName: this.capturedImageTitle || 'foto', - Files: this.seletedContent, - /* FileExtension: 'jpeg', */ - } - - /* } else if (this.capturedVideo != '') { - this.publication = { - DateIndex: date, - DocumentId: null, - ProcessId: this.folderId, - Title: this.pub.Title, - Message: this.pub.Message, - DatePublication: date, - OriginalFileName: this.capturedImageTitle || 'video', - Files: this.seletedContent, - FileExtension: 'mp4', - } - } */ - - - const loader = this.toastService.loading() - - try { - - - await this.publications.CreatePublication(this.folderId, this.publication).toPromise(); - this.httpErrorHandle.httpsSucessMessagge('Criar publicação') - if (window["sharedContent"]) { - - window["sharedContent"] = null - window["openFolder"] = true - - if(window.innerWidth <= 700) { - this.router.navigate(['/home/publications', this.folderId]); - } else if(window.innerWidth >= 701){ - let navigationExtras: NavigationExtras = { queryParams: { "folderId": this.folderId, } }; - this.router.navigate(['/home/publications']); - } - - return - } - - this.close(); - } catch (error) { - this.httpErrorHandle.httpStatusHandle(error) - } finally { - loader.remove() - } - - } - - this.PublicationFolderService.getPublicationsIds(this.folderId) + this.close(); + this.PublicationFromMvService.setFolderId(this.folderId) + await this.PublicationFromMvService.save() } else { this.httpErrorHandle.validationMessagge("noFileSelected") } } + ngOnDestroy() { + // if(!this.PublicationFromMvService.form.send) { + // this.PublicationFromMvService.cancel() + // } + } + close() { - this.modalController.dismiss(this.publication).then(() => { + this.modalController.dismiss(this.PublicationFromMvService.form).then(() => { this.showLoader = true; }); @@ -566,7 +440,7 @@ export class NewPublicationPage implements OnInit { clear() { this.capturedImageTitle = null; - this.seletedContent = []; + this.PublicationFromMvService.form.Files = []; } setTitle() { @@ -578,8 +452,6 @@ export class NewPublicationPage implements OnInit { } else if (this.publicationType == '3') { this.publicationTitle = 'Editar Publicação'; - this.pub = this.navParams.get('publication'); - } } @@ -603,7 +475,7 @@ export class NewPublicationPage implements OnInit { deletePublicationImage() { - this.seletedContent = [] + this.PublicationFromMvService.form.Files = [] } async compressImageBase64(base64String: string, maxWidth: number, maxHeight: number, quality: number): Promise { @@ -794,7 +666,7 @@ console.log(stringGerada); } deleteFromSeletedContent(index) { - this.seletedContent.splice(index, 1) + this.PublicationFromMvService.form.Files.splice(index, 1) } closeApp() { @@ -806,73 +678,84 @@ console.log(stringGerada); } - async recordevideoIos(fullPath) { - console.log('fullpath', fullPath) + async recordevideoIos(fullPath, element) { + try { - const directory = await Filesystem.getUri({ - directory: Directory.Cache, - path: '', - }); + const directory = await Filesystem.getUri({ + directory: Directory.Cache, + path: '', + }); - const stringGerada = this.gerarStringAleatoria(); -console.log(stringGerada); - let fileObject ={}; - this.videoconvertService.convertVideo(fullPath,directory.uri,stringGerada,'mp4').then(async () => { - await Filesystem.readFile({ path: `${directory.uri}${stringGerada}.mp4`}) + const stringGerada = this.gerarStringAleatoria(); - .then(async (content) => { - this.filecontent = true; - fileObject = {} - console.log('First clean',fileObject) - fileObject = { - FileBase64: 'data:video/mp4;base64,' + content.data, - FileExtension: 'mp4', - OriginalFileName: stringGerada - } - console.log('what do we have',fileObject) - this.seletedContent.push(fileObject) - console.log('file object 1',fileObject) - fileObject ={}; - const deleteSecretFile = async () => { - await Filesystem.deleteFile({ - path: `${stringGerada}.mp4`, - directory: Directory.Cache, - }); - }; - await deleteSecretFile().then((value) => { - console.log('delete file',value) - fileObject ={}; - console.log('file object 2',fileObject) + this.videoconvertService.convertVideo(fullPath,directory.uri,stringGerada,'mp4').then(async () => { + await Filesystem.readFile({ path: `${directory.uri}${stringGerada}.mp4`}) + + .then(async (content) => { + this.filecontent = true; + + const file = new File([element.blob], element.name); + + const newAttachment = new PublicationAttachmentEntity( + { + base64: 'data:video/mp4;base64,' + content.data, + extension: 'mp4', + blobFile: file, + FileType: this.checkFileType.checkFileType('mp4') as any, + OriginalFileName: 'load video' + } + ) + + this.PublicationFromMvService.form.Files.push(newAttachment) + + const deleteSecretFile = async () => { + await Filesystem.deleteFile({ + path: `${stringGerada}.mp4`, + directory: Directory.Cache, + }); + }; + await deleteSecretFile().then((value) => { + console.log('delete file',value) + }) }) - }) - .catch((erro) => console.error('read converted video erro ', erro)); - }); + .catch((erro) => console.error('read converted video erro ', erro)); + }); - } catch (error) { + } catch (error) { console.log('record video ios erro, ', error) - } + } } - async recordVideoAndroid(fullPath) { + async recordVideoAndroid(fullPath, element) { try { - const savedFile = await Filesystem.copy({ - from: fullPath, - to: "video.mp4", - toDirectory: FilesystemDirectory.Data - }); - console.log(savedFile.uri) - Filesystem.readFile({ path: savedFile.uri }) + const savedFile = await Filesystem.copy({ + from: fullPath, + to: "video.mp4", + toDirectory: FilesystemDirectory.Data + }); + console.log(savedFile.uri) + Filesystem.readFile({ path: savedFile.uri }) .then(async (content) => { + this.filecontent = true; - let fileObject = { - FileBase64: 'data:video/mp4;base64,' + content.data, - FileExtension: 'mp4', - OriginalFileName: 'video' - } - this.seletedContent.push(fileObject) + + const file = new File([element.blob], element.name); + window['a'] = element + const newAttachment = new PublicationAttachmentEntity( + { + base64: 'data:video/mp4;base64,' + content.data, + extension: 'mp4', + blobFile: file, + FileType: this.checkFileType.checkFileType( 'mp4') as any, + OriginalFileName: 'load video' + } + ) + this.PublicationFromMvService.form.Files.push(newAttachment) + + }) .catch((error) => console.error('reade converted video erro ',error)); @@ -889,24 +772,38 @@ console.log(stringGerada); Filesystem.readFile({ path: resultUrl }) .then(async (content) => { - console.log(content) + this.filecontent = true; - let fileObject; + if (this.removeTextBeforeSlash(element.mimeType, '/') == "mp4") { - fileObject = { - FileBase64: 'data:video/mp4;base64,' + content.data, - FileExtension: this.removeTextBeforeSlash(element.mimeType, '/'), - OriginalFileName: 'video' - } + + const newAttachment = new PublicationAttachmentEntity( + { + base64: content.data, + extension: this.removeTextBeforeSlash(element.mimeType, '/'), + FileType: this.checkFileType.checkFileType( this.removeTextBeforeSlash(element.mimeType, '/')) as any, + OriginalFileName: 'load video' + } + ) + + newAttachment.needUpload() + this.PublicationFromMvService.form.Files.push(newAttachment) + } else { - fileObject = { - FileBase64: 'data:image/jpeg;base64,' + content.data, - FileExtension: this.removeTextBeforeSlash(element.mimeType, '/'), - OriginalFileName: 'image' - } + + const newAttachment = new PublicationAttachmentEntity( + { + base64: 'data:image/jpeg;base64,' + content.data, + extension: this.removeTextBeforeSlash(element.mimeType, '/'), + FileType: this.checkFileType.checkFileType( this.removeTextBeforeSlash(element.mimeType, '/')) as any, + OriginalFileName: 'image' + } + ) + + this.PublicationFromMvService.form.Files.push(newAttachment) } - this.seletedContent.push(fileObject) + }) .catch((err) => console.error(err)); @@ -939,7 +836,7 @@ console.log(stringGerada); } console.log('shared base', content.data) - this.seletedContent.push(fileObject) + this.PublicationFromMvService.form.Files.push(fileObject) } catch (error) { console.log('error shared filesystem', error) } @@ -963,12 +860,18 @@ console.log(stringGerada); FileExtension: 'mp4', OriginalFileName: 'shared', } */ - fileObject = { - FileBase64: 'data:video/mp4;base64,' + this.removeTextBeforeSlash(content.data, ','), - FileExtension: 'mp4', - OriginalFileName: 'shared', - } - this.seletedContent.push(fileObject) + + const newAttachment = new PublicationAttachmentEntity( + { + base64: 'data:video/mp4;base64,' + this.removeTextBeforeSlash(content.data, ','), + extension: 'mp4', + FileType: this.checkFileType.checkFileType('mp4') as any, + OriginalFileName: 'shared' + } + ) + newAttachment.needUpload() + + this.PublicationFromMvService.form.Files.push(newAttachment) fileObject ={}; const deleteSecretFile = async () => { await Filesystem.deleteFile({ @@ -1014,7 +917,7 @@ console.log(stringGerada); } console.log('shared base', content.data) - this.seletedContent.push(fileObject) + this.PublicationFromMvService.form.Files.push(fileObject) } catch (error) { console.log('error shared filesystem', error) } diff --git a/src/app/pages/publications/view-publications/view-publications.page.ts b/src/app/pages/publications/view-publications/view-publications.page.ts index 306b947b2..c568a64c5 100644 --- a/src/app/pages/publications/view-publications/view-publications.page.ts +++ b/src/app/pages/publications/view-publications/view-publications.page.ts @@ -21,6 +21,8 @@ import { StopvideoService } from "src/app/services/stopvideo.service" import { Result } from 'neverthrow'; import { App } from '@capacitor/app'; import { ActiveTabService } from 'src/app/services/active-tab.service'; +import { PublicationHolderService } from 'src/app/services/publication/publication-holder.service' + @Component({ selector: 'app-view-publications', templateUrl: './view-publications.page.html', @@ -71,7 +73,8 @@ export class ViewPublicationsPage implements OnInit { private publicationVideoManagerService: PublicationVideoManagerService, public stopvideoService: StopvideoService, private platform: Platform, - public activeTabService: ActiveTabService) { + public activeTabService: ActiveTabService, + public PublicationHolderService: PublicationHolderService) { /* this.publicationVideoManagerService.setContainer(this.VideoManager.nativeElement) */ @@ -311,20 +314,26 @@ export class ViewPublicationsPage implements OnInit { } async AddPublication(publicationType: any, folderId: any) { - const modal = await this.modalController.create({ - component: NewPublicationPage, - componentProps: { - publicationType: publicationType, - folderId: this.folderId, - }, - cssClass: 'new-publication modal modal-desktop', - backdropDismiss: false - }); - modal.onDidDismiss().then(() => { - this.doRefresh(event); - }); - await modal.present(); + // if(this.PublicationHolderService.PublicationFormMV.length == 0) { + const modal = await this.modalController.create({ + component: NewPublicationPage, + componentProps: { + publicationType: publicationType, + folderId: this.folderId, + }, + cssClass: 'new-publication modal modal-desktop', + backdropDismiss: false + }); + + modal.onDidDismiss().then(() => { + this.doRefresh(event); + }); + await modal.present(); + //} else { + // this.toastService._successMessage('já existe uma publicação a ser processado'); + //} + } goToPublicationDetail(DocumentId: string, ProcessId: string) { diff --git a/src/app/services/chat/chat-system.service.ts b/src/app/services/chat/chat-system.service.ts index 8ac80a56c..f7b2089d0 100644 --- a/src/app/services/chat/chat-system.service.ts +++ b/src/app/services/chat/chat-system.service.ts @@ -151,15 +151,6 @@ export class ChatSystemService { } catch(error) {} } - setMainChangeDetector(x:Function) { - this.mainChangeDetector = x - } - - runMainChangeDetector() { - console.log("change") - // this.mainChangeDetector() - } - loadChat() { if (SessionStore.user?.ChatData?.data) { this.ReLoadChat() diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index 63a8dd45f..3767b9518 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -25,7 +25,6 @@ import { ChatSystemService } from './chat-system.service'; import { ViewedMessageService } from './viewed-message.service' import * as FIFOProcessQueue from 'fifo-process-queue'; import { NotificationsService } from '../notifications.service'; -import { ChangeDetectorRef } from '@angular/core'; @Injectable({ providedIn: 'root' @@ -85,7 +84,6 @@ export class RoomService { sortRoomList = () => { } chatServiceDeleteRoom = (roomId) => { } - private changeDetector: Function = () => {} constructor( public RochetChatConnectorService: RochetChatConnectorService, @@ -192,11 +190,6 @@ export class RoomService { } - setChangeDetector(x:Function) { - console.log("set change detector") - this.changeDetector = x - } - get online() { if (!this.isGroup) { diff --git a/src/app/services/notifications.service.ts b/src/app/services/notifications.service.ts index 750711340..8a26feedf 100644 --- a/src/app/services/notifications.service.ts +++ b/src/app/services/notifications.service.ts @@ -202,9 +202,6 @@ export class NotificationsService { this.active = true console.log('NOtification Listener', notification) this.storenotification(notification) - this.chatNotification(notification) - - } ); @@ -216,7 +213,6 @@ export class NotificationsService { this.eventtrigger.publishSomeData({ notification: "recive" }) - this.chatNotification(notification) // Handle the received message, e.g., show a notification }); } @@ -400,12 +396,4 @@ export class NotificationsService { } - chatNotification(_notification) { - const notification = this.NotificationHolderService.stractureNotificationObject(_notification) - - if (notification?.notification?.data?.Service === "chat" || notification?.Service === "chat") { - this.ChatController.ChatSystemService.runMainChangeDetector() - } - } - } diff --git a/src/app/services/publication/holder.service.spec.ts b/src/app/services/publication/holder.service.spec.ts new file mode 100644 index 000000000..6faab2556 --- /dev/null +++ b/src/app/services/publication/holder.service.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { HolderService } from './holder.service'; + +describe('HolderService', () => { + let service: HolderService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(HolderService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); diff --git a/src/app/shared/publication/upload/publication-form-mv.service.ts b/src/app/services/publication/holder.service.ts similarity index 72% rename from src/app/shared/publication/upload/publication-form-mv.service.ts rename to src/app/services/publication/holder.service.ts index 7fbeee014..302c7873d 100644 --- a/src/app/shared/publication/upload/publication-form-mv.service.ts +++ b/src/app/services/publication/holder.service.ts @@ -3,7 +3,7 @@ import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) -export class PublicationFormMVService { +export class HolderService { constructor() { } } diff --git a/src/app/services/publication/publication-holder.service.spec.ts b/src/app/services/publication/publication-holder.service.spec.ts new file mode 100644 index 000000000..e89d9e0ec --- /dev/null +++ b/src/app/services/publication/publication-holder.service.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { PublicationHolderService } from './publication-holder.service'; + +describe('PublicationHolderService', () => { + let service: PublicationHolderService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(PublicationHolderService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); diff --git a/src/app/services/publication/publication-holder.service.ts b/src/app/services/publication/publication-holder.service.ts new file mode 100644 index 000000000..efcf34b3b --- /dev/null +++ b/src/app/services/publication/publication-holder.service.ts @@ -0,0 +1,98 @@ +import { Injectable } from '@angular/core'; +import { PublicationFormMV } from 'src/app/shared/publication/upload/upload-streaming.service'; + +@Injectable({ + providedIn: 'root' +}) +export class PublicationHolderService { + + count = 0 + PublicationFormMV: { + id: string, + percentage: number, + retry: boolean, + retryFunction: Function + }[] = [] + + constructor() { + + window['upload-header-set-percentage'] = (id: string, percentage: number) => { + this.PublicationFormMV = this.PublicationFormMV.map((e)=> { + if(e.id == id) { + console.log("percentage", percentage) + e.percentage = percentage + } + return e + }) + + + this.uploadPercentage() + } + + window['upload-header-set-add'] = (id: string, percentage: number, save: Function) => { + this.PublicationFormMV.push({id, percentage, retry: false, retryFunction: save}) + this.uploadPercentage() + } + + + window['upload-header-set-remove'] = (id: string) => { + this.remove(id) + } + + + window['upload-header-set-retry'] = (id: string) => { + + this.PublicationFormMV = this.PublicationFormMV.map((e)=> { + if(e.id == id) { + e.retry = true + } + return e + }) + + this.uploadPercentage() + } + + window['upload-header-remove-retry'] = (id: string) => { + this.uploadPercentage() + + this.PublicationFormMV = this.PublicationFormMV.map((e)=> { + if(e.id == id) { + e.retry = false + } + return e + }) + + + this.uploadPercentage() + + } + + } + + remove(id: string) { + this.PublicationFormMV = this.PublicationFormMV.filter((e)=> e.id != id) + this.uploadPercentage() + } + + hasPublication() { + return this.PublicationFormMV.length >= 1 + } + + + uploadPercentage = () => { + + const percentageArray = this.PublicationFormMV.map((e) => e.percentage) + + // Check if the array is not empty + if (percentageArray.length === 0) { + this.count = 0 + } else { + let sum = percentageArray.reduce((acc, percentage) => acc + percentage, 0); + + // Calculate the average percentage + let averagePercentage = sum / percentageArray.length; + + this.count = Math.ceil(averagePercentage) + } + } +} diff --git a/src/app/services/socket-connection-mcr.service.ts b/src/app/services/socket-connection-mcr.service.ts index 0dd13e48e..b39836fbf 100644 --- a/src/app/services/socket-connection-mcr.service.ts +++ b/src/app/services/socket-connection-mcr.service.ts @@ -147,21 +147,29 @@ class ReconnectingWebSocketSignalR { } commit(path): Promise> { + console.log('committing') return new Promise((resolve, reject) => { - try { - console.log('this.connection.invoke', this.connection) - this.connection.invoke("CommitUpload", path).then((e) => { - console.log("commit message", e) - resolve(ok(true)) - }).catch(err => { - console.error('upload catch commit error') + if(this.isOpen) { + try { + console.log('this.connection.invoke', this.connection) + this.connection.invoke("CommitUpload", path).then((e) => { + console.log("commit message", e) + resolve(ok(true)) + }).catch(err => { + console.error('upload catch commit error') + resolve(Err(false)) + console.error(err.toString()) + }); + } catch(error) { resolve(Err(false)) - console.error(err.toString()) - }); - } catch(error) { - resolve(Err(false)) - console.error('upload commit error') - console.error(error) + console.error('upload commit error') + console.error(error) + } + + } else { + this.onConnect.push(()=> { + resolve(this.commit(path)) + }) } }) } @@ -410,61 +418,60 @@ export class ObjectMergeNotification{ this.runWatch = false }) - this.socket.subscribe((data: socketResponse) => { - if(data.IsCompleted == true) { - console.log("==================!!!====================") - try { - this.callbacks[data.Guid](data) - delete this.callbacks[data.Guid] - } catch (error) {} - } else { - console.log("else", data) - } - }) + // this.socket.subscribe((data: socketResponse) => { + // if(data.IsCompleted == true) { + // console.log("==================!!!====================") + // try { + // this.callbacks[data.Guid](data) + // delete this.callbacks[data.Guid] + // } catch (error) {} + // } else { + // console.log("else", data) + // } + // }) - // this.socket.connect(); // this.watch() } connect() { -// this.socket.connect(); + this.socket.connect(); } close() { - // this.socket.disconnect(); - // this.watchCount = 0; - // this.runWatch = false + this.socket.disconnect(); + this.watchCount = 0; + this.runWatch = false } async watch() { - // this.watchCount = 0; + this.watchCount = 0; - // if(this.runWatch) { - // setTimeout(async () => { - // for(const [key, funx] of Object.entries(this.callbacks)) { + if(this.runWatch) { + setTimeout(async () => { + for(const [key, funx] of Object.entries(this.callbacks)) { - // const request = await this.CMAPIService.getVideoHeader(key) + const request = await this.CMAPIService.getVideoHeader(key) - // if(request.isOk()) { - // funx() - // delete this.callbacks[key] - // } - // } + if(request.isOk()) { + funx() + delete this.callbacks[key] + } + } - // this.watchCount++ - // if(this.watchCount <= 15) { - // this.watch() - // } else { - // this.runWatch = false - // } + this.watchCount++ + if(this.watchCount <= 15) { + this.watch() + } else { + this.runWatch = false + } - // }, 1000) + }, 1000) - // } else { - // console.log("end loop============================") - // } + } else { + console.log("end loop============================") + } } subscribe(GUID, callback:Function) { diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index 140f92715..9fcd1d54b 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -30,7 +30,6 @@ import { SessionStore } from 'src/app/store/session.service'; import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { PermissionService } from 'src/app/services/permission.service'; import { FileValidatorService } from "src/app/services/file/file-validator.service" -import { ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-group-messages', templateUrl: './group-messages.page.html', @@ -103,8 +102,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe private platform: Platform, private fileOpener: FileOpener, public p: PermissionService, - private FileValidatorService: FileValidatorService, - private ChangeDetectorRef: ChangeDetectorRef + private FileValidatorService: FileValidatorService ) { this.ChatSystemService.getUser() @@ -120,9 +118,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe this.ChatSystemService.openRoom(this.roomId) this.ChatSystemService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked this.groupNameFormart = this.ChatSystemService.getGroupRoom(this.roomId).name.split('-').join(' ') - this.ChatSystemService.getGroupRoom(this.roomId).setChangeDetector(()=> { - this.changeDetector() - }) this.showAvatar = false setTimeout(() => { @@ -134,12 +129,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } - changeDetector = () => { - console.log('run detection shared') - this.ChangeDetectorRef.detectChanges() - } - - ngOnInit() { this.loggedUser = this.loggedUserChat; //setTimeout(() => { diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 22276c683..22fa3ebb6 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -34,7 +34,6 @@ import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { ChatMessageDebuggingPage } from 'src/app/shared/popover/chat-message-debugging/chat-message-debugging.page'; import { PermissionService } from 'src/app/services/permission.service'; import { FileValidatorService } from "src/app/services/file/file-validator.service" -import { ChangeDetectorRef } from '@angular/core'; const IMAGE_DIR = 'stored-images'; @@ -124,8 +123,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy private platform: Platform, private fileOpener: FileOpener, public p: PermissionService, - private FileValidatorService: FileValidatorService, - private ChangeDetectorRef: ChangeDetectorRef + private FileValidatorService: FileValidatorService ) { // update this.checkAudioPermission() @@ -141,9 +139,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy this.ChatSystemService.openRoom(this.roomId) this.ChatSystemService.getDmRoom(this.roomId) - this.ChatSystemService.getDmRoom(this.roomId).setChangeDetector(()=> { - this.changeDetector() - }) this.showAvatar = false @@ -161,11 +156,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } - changeDetector = () => { - console.log('run detection shared') - this.ChangeDetectorRef.detectChanges() - } - async ChatMessageDebuggingPage() { diff --git a/src/app/shared/header/header.page.html b/src/app/shared/header/header.page.html index 29569306c..fd43c232a 100644 --- a/src/app/shared/header/header.page.html +++ b/src/app/shared/header/header.page.html @@ -40,14 +40,23 @@
-
+
+
+ {{ PublicationHolderService.count }}% + + X +
-
+
-
+
Anexos
-
+
diff --git a/src/app/shared/publication/new-publication/new-publication.page.ts b/src/app/shared/publication/new-publication/new-publication.page.ts index 20407b9a4..e2b67db98 100644 --- a/src/app/shared/publication/new-publication/new-publication.page.ts +++ b/src/app/shared/publication/new-publication/new-publication.page.ts @@ -20,10 +20,11 @@ import { environment } from 'src/environments/environment'; import { CaptureImageOptions, MediaCapture } from '@awesome-cordova-plugins/media-capture/ngx'; import { Directory, Filesystem, FilesystemDirectory } from '@capacitor/filesystem'; import { Platform } from '@ionic/angular'; -import { PublicationAttachmentEntity, PublicationFormMV } from '../upload/upload-streaming.service'; -import { PublicationFormMVService } from "src/app/shared/publication/upload/publication-form-mv.service" +import { PublicationAttachmentEntity } from '../upload/upload-streaming.service'; import { VideoconvertService } from 'src/app/services/videoconvert.service'; - +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 { newRapid = "1", new = "2", @@ -68,11 +69,8 @@ export class NewPublicationPage implements OnInit { photoOrVideo: boolean = false; video: any; - publicationFormMV = new PublicationFormMV() - - constructor( - PublicationFormMVService: PublicationFormMVService, + public PublicationFromMvService: PublicationFromMvService, public photoService: PhotoService, private publications: PublicationsService, private toastService: ToastService, @@ -87,9 +85,12 @@ export class NewPublicationPage implements OnInit { private MiddlewareServiceService: MiddlewareServiceService, private LakefsRepositoryService: LakefsRepositoryService, private SocketConnectionMCRService: SocketConnectionMCRService, - private videoconvertService: VideoconvertService + private videoconvertService: VideoconvertService, + public UploadStreamingService: UploadStreamingService ) { this.publicationTitle = 'Nova Publicação'; + this.PublicationFromMvService.clear() + } ngOnInit() { @@ -124,8 +125,8 @@ export class NewPublicationPage implements OnInit { processData(res) { console.log("res process", res) - this.publicationFormMV.form.Files = [] - this.publicationFormMV.form.setData({ + this.PublicationFromMvService.form.Files = [] + this.PublicationFromMvService.form.setData({ DateIndex: res.DateIndex, DocumentId: res.DocumentId, ProcessId: res.ProcessId, @@ -146,7 +147,7 @@ export class NewPublicationPage implements OnInit { }) for(const files of newFiles) { - this.publicationFormMV.form.Files.push(files) + this.PublicationFromMvService.form.Files.push(files) } } @@ -181,7 +182,7 @@ export class NewPublicationPage implements OnInit { FileType: 'image' } ) - this.publicationFormMV.form.Files.push(newAttachment) + this.PublicationFromMvService.form.Files.push(newAttachment) }); } @@ -215,7 +216,8 @@ export class NewPublicationPage implements OnInit { } ) //newAttachment.needUpload(); - this.publicationFormMV.form.Files.push(newAttachment) + + this.PublicationFromMvService.form.Files.push(newAttachment) }); } @@ -252,12 +254,14 @@ export class NewPublicationPage implements OnInit { } ) - // newAttachment.needUpload() - this.publicationFormMV.form.Files.push(newAttachment) + + + newAttachment.needUpload() + this.PublicationFromMvService.form.Files.push(newAttachment) this.filecontent = true; } else { - if (this.publicationFormMV.form.Files.length === 0) + if (this.PublicationFromMvService.form.Files.length === 0) this.filesSizeSum = 0 this.httpErroHandle.validationMessagge('filessize'); @@ -300,7 +304,7 @@ export class NewPublicationPage implements OnInit { }) /* fileObject.needUpload() */ - this.publicationFormMV.form.Files.push(fileObject) + this.PublicationFromMvService.form.Files.push(fileObject) }) .catch((err) => console.error(err)); } catch (error) { @@ -309,7 +313,7 @@ export class NewPublicationPage implements OnInit { } } else { - if (this.publicationFormMV.form.Files.length === 0) + if (this.PublicationFromMvService.form.Files.length === 0) this.filesSizeSum = 0 this.httpErrorHandle.validationMessagge('filessize') @@ -325,11 +329,11 @@ export class NewPublicationPage implements OnInit { injectValidation() { this.Form = new FormGroup({ - Subject: new FormControl(this.publicationFormMV.form.Title, [ + Subject: new FormControl(this.PublicationFromMvService.form.Title, [ Validators.required, // Validators.minLength(4) ]), - Message: new FormControl(this.publicationFormMV.form.Message, [ + Message: new FormControl(this.PublicationFromMvService.form.Message, [ Validators.required, Validators.maxLength(1000) ]) @@ -346,149 +350,32 @@ export class NewPublicationPage implements OnInit { return false } + this.PublicationFromMvService.setFolderId(this.folderId) + this.goBack(); + await this.PublicationFromMvService.save() - if (this.publicationType == ActionType.edit) { - - if (this.publicationFormMV.form.Files.length >= 1) { - const loader = this.toastService.loading() - - const upload = await this.publicationFormMV.uploadVideosFiles() - - if(upload) { - this.publicationFormMV.form.Files = this.publicationFormMV.form.Files.map((e:PublicationAttachmentEntity) => { - if(e.FileType == 'video' && e.blobFile && e.toUpload) { - e.OriginalFileName = e?.chucksManager?.path?.replace(".mp4", "") || e.OriginalFileName - e.FileExtension = "mp4" - } - return e - }) - - } - - const publication: any = Object.assign({}, this.publicationFormMV.form) - - publication.Files = publication.Files.map( (e:PublicationAttachmentEntity) => ({ - FileBase64: e.url, - FileExtension: e.FileExtension, - OriginalFileName: e.OriginalFileName || 'foto' - })) - - try { - - const response = await this.publications.UpdatePublication(publication.ProcessId, publication).toPromise() - - this.httpErroHandle.httpsSucessMessagge('Editar publicação') - - this.goBack(); - - } catch (error) { - this.httpErroHandle.httpStatusHandle(error) - if (error.status == 404) { - this.PublicationFolderService.deletePost(this.publicationFormMV.form.ProcessId, this.publicationFormMV.form.DocumentId) - this.goBack(); - } - } finally { - loader.remove() - } - - - } else { - this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo") - } - - - } - else { - let time = new Date() - if (this.publicationFormMV.form.Files.length >= 1) { - - const loader = this.toastService.loading() - - const upload = await this.publicationFormMV.uploadVideosFiles() - - console.log({upload}) - - if(upload) { - this.publicationFormMV.form.Files = this.publicationFormMV.form.Files.map((e:PublicationAttachmentEntity) => { - if(e.FileType == 'video' && e.blobFile && e.toUpload) { - e.OriginalFileName = e.chucksManager.path.replace(".mp4", "") - e.FileExtension = "mp4" - e.Base64 = '' - } - - if(e.FileType == 'video' && !e.toUpload) { - e.Base64 = e.url - } - - - return e - }) - - - - const publication: any = Object.assign({}, this.publicationFormMV.form) - - publication.Files = publication.Files.map( (e:PublicationAttachmentEntity) => ({ - FileBase64: e.Base64, - FileExtension: e.FileExtension, - OriginalFileName: e.OriginalFileName || 'foto' - })) - - publication.DocumentId = null; - publication.ProcessId = this.folderId - - - - try { - - await this.publications.CreatePublication(publication.ProcessId, publication).toPromise() - if (this.publicationTitle == '1') { - - } else if (this.publicationTitle == '2') { - this.httpErroHandle.httpsSucessMessagge('Criar publicação') - } else if (this.publicationTitle == '3') { - this.httpErroHandle.httpsSucessMessagge('Editar publicação') - } - - this.goBackToViewPublications.emit(); - } catch (error) { - this.httpErroHandle.httpStatusHandle(error) - } finally { - loader.remove() - } - - } else { - this.toastService._badRequest("Tive um erro ao enviar o ficheiro") - loader.remove() - } - - - - } else { - this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo") - } - - } - - - this.publicationFormMV.ObjectMergeNotification.close() + // this.PublicationHolderService.setPublication(this.PublicationFromMvService) } ngOnDestroy() { - this.publicationFormMV.ObjectMergeNotification.close() + // if(!this.PublicationFromMvService.form.send) { + // this.PublicationFromMvService.cancel() + // } } + + close() { this.goBack(); } clear() { - this.publicationFormMV.form.Files = []; + this.PublicationFromMvService.form.Files = []; } deletePublicationImage() { - this.publicationFormMV.form.Files = [] + this.PublicationFromMvService.form.Files = [] } setAction() { @@ -728,7 +615,7 @@ export class NewPublicationPage implements OnInit { } deleteFromSeletedContent(index) { - this.publicationFormMV.form.Files.splice(index, 1) + this.PublicationFromMvService.form.Files.splice(index, 1) } chossePhotoOrVideo() { @@ -750,7 +637,7 @@ export class NewPublicationPage implements OnInit { this.recordVideoPc(element.fullPath) } } else { - if (this.publicationFormMV.form.Files.length === 0) + if (this.PublicationFromMvService.form.Files.length === 0) this.filesSizeSum = 0 this.httpErrorHandle.validationMessagge('filessize') @@ -798,7 +685,7 @@ console.log(stringGerada); } ) /* fileObject.needUpload() */ - this.publicationFormMV.form.Files.push(fileObject) + this.PublicationFromMvService.form.Files.push(fileObject) }) .catch((erro) => console.error('read converted video erro ', erro)); } catch (error) { @@ -840,7 +727,7 @@ console.log(stringGerada); } /* fileObject.needUpload() */ - this.publicationFormMV.form.Files.push(fileObject) + this.PublicationFromMvService.form.Files.push(fileObject) }) .catch((err) => console.error(err)); } catch (error) { diff --git a/src/app/shared/publication/upload/publication-form-mv.service.spec.ts b/src/app/shared/publication/upload/publication-from-mv.service.spec.ts similarity index 50% rename from src/app/shared/publication/upload/publication-form-mv.service.spec.ts rename to src/app/shared/publication/upload/publication-from-mv.service.spec.ts index e29f538fa..b79d741c5 100644 --- a/src/app/shared/publication/upload/publication-form-mv.service.spec.ts +++ b/src/app/shared/publication/upload/publication-from-mv.service.spec.ts @@ -1,13 +1,13 @@ import { TestBed } from '@angular/core/testing'; -import { PublicationFormMVService } from './publication-form-mv.service'; +import { PublicationFromMvService } from './publication-from-mv.service'; -describe('PublicationFormMVService', () => { - let service: PublicationFormMVService; +describe('PublicationFromMvService', () => { + let service: PublicationFromMvService; beforeEach(() => { TestBed.configureTestingModule({}); - service = TestBed.inject(PublicationFormMVService); + service = TestBed.inject(PublicationFromMvService); }); it('should be created', () => { diff --git a/src/app/shared/publication/upload/publication-from-mv.service.ts b/src/app/shared/publication/upload/publication-from-mv.service.ts new file mode 100644 index 000000000..556fac3e0 --- /dev/null +++ b/src/app/shared/publication/upload/publication-from-mv.service.ts @@ -0,0 +1,356 @@ + +import { Injectable } from '@angular/core'; +import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; +import { PublicationsService } from 'src/app/services/publications.service'; +import { ToastService } from 'src/app/services/toast.service'; +import { PublicationFolderService } from 'src/app/store/publication-folder.service'; +import { Chunks, ChunksBase64, IOUploadError, PublicationAttachmentEntity, PublicationFormModel, UploadFileUseCase } from './upload-streaming.service'; +import { ObjectMergeNotification } from 'src/app/services/socket-connection-mcr.service'; +import { v4 as uuidv4 } from 'uuid' +import { Result } from 'neverthrow'; +import { IPublicationFormModelEntity } from '../new-publication/interface/interface'; +import { CMAPIService } from "src/app/shared/repository/CMAPI/cmapi.service" + +enum ActionType { + newRapid = "1", + new = "2", + edit = "3" +} + +@Injectable({ + providedIn: 'any' +}) +export class PublicationFromMvService { + + id: string = uuidv4() + private UploadFileUseCase = new UploadFileUseCase() + form = new PublicationFormModel() + ObjectMergeNotification = new ObjectMergeNotification() + totalPercentage = 0 + publicationType: ActionType + folderId: string + + + constructor( + private publications: PublicationsService, + private toastService: ToastService, + private httpErroHandle: HttpErrorHandle, + public PublicationFolderService: PublicationFolderService, + private CMAPIService: CMAPIService, + public publicationFolderService: PublicationFolderService + ) {} + + + clear() { + + + + this.id = uuidv4() + this.UploadFileUseCase = new UploadFileUseCase() + this.form = new PublicationFormModel() + this.ObjectMergeNotification = new ObjectMergeNotification() + this.totalPercentage = 0 + + this.ObjectMergeNotification.connect(); + + window['upload-header-set-add'](this.id, this.totalPercentage, this.save) + } + + cancel() { + window['upload-header-set-remove'](this.id) + } + + + setFolderId(folderId) { + this.folderId = folderId + } + + save = async() => { + + if (this.publicationType == ActionType.edit) { + + if (this.form.Files.length >= 1) { + // const loader = this.toastService.loading() + + this.form.send = true + const upload = await this.uploadVideosFiles() + + if(upload) { + this.form.Files = this.form.Files.map((e:PublicationAttachmentEntity) => { + if(e.FileType == 'video' && e.toUpload) { + e.OriginalFileName = e?.chucksManager?.path?.replace(".mp4", "") || e.OriginalFileName + e.FileExtension = e.FileExtension || "mp4" + } + return e + }) + + } + + const publication: any = Object.assign({}, this.form) + + publication.Files = publication.Files.map( (e:PublicationAttachmentEntity) => ({ + FileBase64: e.url, + FileExtension: e.FileExtension, + OriginalFileName: e.OriginalFileName || 'foto' + })) + + try { + + const response = await this.publications.UpdatePublication(publication.ProcessId, publication).toPromise() + + this.httpErroHandle.httpsSucessMessagge('Editar publicação') + this.publicationFolderService.getPublicationsIds(this.folderId) + + // this.goBack(); + + } catch (error) { + this.httpErroHandle.httpStatusHandle(error) + if (error.status == 404) { + this.PublicationFolderService.deletePost(this.form.ProcessId, this.form.DocumentId) + // this.goBack(); + } + } finally { + // loader.remove() + } + + + } else { + this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo") + } + + + } + else { + let time = new Date() + if (this.form.Files.length >= 1) { + + // const loader = this.toastService.loading() + + this.form.send = false + const upload = await this.uploadVideosFiles() + + if(upload) { + this.form.Files = this.form.Files.map((e:PublicationAttachmentEntity) => { + if(e.FileType == 'video' && e.toUpload) { + e.OriginalFileName = e.chucksManager.path.replace(".mp4", "") + e.FileExtension = e.FileExtension || "mp4" + e.Base64 = '' + } + + if(e.FileType == 'video' && !e.toUpload) { + e.Base64 = e.url + } + + + return e + }) + + + + const publication: any = Object.assign({}, this.form) + + publication.Files = publication.Files.map( (e:PublicationAttachmentEntity) => ({ + FileBase64: e.Base64, + FileExtension: e.FileExtension, + OriginalFileName: e.OriginalFileName || 'foto' + })) + + publication.DocumentId = null; + publication.ProcessId = this.folderId + + + + try { + + await this.publications.CreatePublication(publication.ProcessId, publication).toPromise() + + if (this.publicationType == '1') { + + } else if (this.publicationType == '2') { + this.httpErroHandle.httpsSucessMessagge('Criar publicação') + } else if (this.publicationType == '3') { + this.httpErroHandle.httpsSucessMessagge('Editar publicação') + } + + // this.goBackToViewPublications.emit(); + window['upload-header-set-remove'](this.id); + this.publicationFolderService.getPublicationsIds(this.folderId) + } catch (error) { + this.httpErroHandle.httpStatusHandle(error) + } finally { + // loader.remove() + } + + } else { + this.toastService._badRequest("ocorreu um erro ao enviar o ficheiro") + // loader.remove() + } + + + + } else { + this.toastService._badRequest("É necessário adicionar uma imagem ou vídeo") + } + + } + + + // this.PublicationHolderService.setPublication(this.publicationFormMV) + this.ObjectMergeNotification.close() + } + + + + + 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: 1000 }) + fileChunks.setFile(fileBlob) + PublicationAttachmentEntity.setChunkManger(fileChunks) + } else { + const Base64 = PublicationAttachmentEntity.Base64; + const fileChunks = new ChunksBase64({chunkSize: 1000 }) + fileChunks.setFile(Base64) + PublicationAttachmentEntity.setChunkManger(fileChunks) + } + + PublicationAttachmentEntity.chucksManager.updateTotalPercentageTrigger = () => { + this.uploadPercentage() + } + + } + + let attemp = 0; + let result: Result + + 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 { + + return new Promise((resolve, reject) => { + + // this.ObjectMergeNotification.socket.registerWhenConnected(() => { + const videosFiles = this.getVideoFiles() + + window['upload-header-set-percentage'](this.id, 1) + window['upload-header-remove-retry'](this.id); + + const videosFilesToUploads = videosFiles.filter( e => e.FileType == "video" && e.toUpload) + + const Promises: Promise[] = [] + + for(const file of videosFilesToUploads) { + const promise = this.upload(file) + Promises.push(promise) + } + + // Use Promise.all to wait for all promises to resolve + Promise.all(Promises) + .then((results) => { + // Check if every promise resolved successfully + const allPromisesResolvedSuccessfully = results.every((result) => result == true); + + if (allPromisesResolvedSuccessfully) { + console.log('All promises resolved successfully.'); + + resolve(true) + } else { + window['upload-header-set-retry'](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 { + console.log("===============!!==========================================") + 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; + } + + } +} diff --git a/src/app/shared/publication/upload/upload-streaming.service.ts b/src/app/shared/publication/upload/upload-streaming.service.ts index 9a5d6eaa5..66f6c649f 100644 --- a/src/app/shared/publication/upload/upload-streaming.service.ts +++ b/src/app/shared/publication/upload/upload-streaming.service.ts @@ -3,7 +3,7 @@ import { ok, err, Result } from 'neverthrow'; import { ObjectMergeNotification } from 'src/app/services/socket-connection-mcr.service'; import { CMAPIService } from "src/app/shared/repository/CMAPI/cmapi.service" import { DomSanitizer } from '@angular/platform-browser'; - +import { v4 as uuidv4 } from 'uuid' export enum UploadError { @@ -26,7 +26,7 @@ export class UploadStreamingService { } } -class UploadFileUseCase { +export class UploadFileUseCase { CMAPIService: CMAPIService = window["CMAPIAPIRepository"] constructor() {} async execute(PublicationAttachmentEntity: PublicationAttachmentEntity): Promise> { @@ -168,7 +168,7 @@ export class PublicationAttachmentEntity { this.toUpload = true } - setChunkManger (chunks: Chunks) { + setChunkManger (chunks: Chunks | ChunksBase64) { this.chucksManager = new ChucksManager({chunks}) } get hasChunkManger() { @@ -178,6 +178,10 @@ export class PublicationAttachmentEntity { get hasChunkManager() { return this.chucksManager != null } + + get hasBlob() { + return this.blobFile + } } interface IPublicationFormModelEntity { @@ -210,6 +214,7 @@ export class PublicationFormModel implements IPublicationFormModelEntity { Files: PublicationAttachmentEntity[] = [] hasSet = false + send = false setData(data: IPublicationFormModelEntity) { if(data.Files) { @@ -224,12 +229,15 @@ 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(); + this.ObjectMergeNotification.connect(); + window['upload-header-set-add'](this.id, this.totalPercentage) } setDataToFrom(data: IPublicationFormModelEntity) { @@ -245,9 +253,11 @@ export class PublicationFormMV { 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 } } @@ -257,20 +267,31 @@ export class PublicationFormMV { return new Promise(async (resolve, reject)=> { if(!PublicationAttachmentEntity.hasChunkManger) { - const fileBlob = PublicationAttachmentEntity.blobFile; - const fileChunks = new Chunks({chunkSize: 50 }) - fileChunks.setFile(fileBlob) - PublicationAttachmentEntity.setChunkManger(fileChunks) + 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() + } - } else if(PublicationAttachmentEntity.chucksManager.doneUpload) { - return resolve(true) } let attemp = 0; let result: Result - if( PublicationAttachmentEntity.chucksManager.isUploading == false) { + if( PublicationAttachmentEntity.chucksManager.isUploading == false && PublicationAttachmentEntity.chucksManager.doneUpload == false) { do { attemp++ @@ -293,7 +314,7 @@ export class PublicationFormMV { } } else if ( PublicationAttachmentEntity.chucksManager.contentReady == false) { - + console.log("try to send again") return await resolve(this.commit(PublicationAttachmentEntity)) } else { @@ -311,6 +332,8 @@ export class PublicationFormMV { // 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[] = [] @@ -328,8 +351,10 @@ export class PublicationFormMV { 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.'); } @@ -344,22 +369,26 @@ export class PublicationFormMV { } - get uploadPercentage() { + uploadPercentage() { const videosFiles = this.getVideoFiles() const percentageArray = videosFiles.map((e) => e.chucksManager.calculatePercentage()) // Check if the array is not empty if (percentageArray.length === 0) { - return null; + 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; } - let sum = percentageArray.reduce((acc, percentage) => acc + percentage, 0); - - // Calculate the average percentage - let averagePercentage = sum / percentageArray.length; - - return averagePercentage; } } @@ -405,6 +434,51 @@ export class Chunks { } +export class ChunksBase64 { + + chunkSize: number + private base64: string + bytes: Uint8Array + + constructor({chunkSize}) { + this.chunkSize = chunkSize * 1024 + } + + get totalChunks () { + return Math.ceil(this.bytes.length / this.chunkSize); + } + + setFile(base64: string) { + this.base64 = base64 + let utf8Encoder = new TextEncoder(); + this.bytes = utf8Encoder.encode(base64); + } + + // Function to read a chunk of the file + async readChunk(start: number, end: number) { + + // Slice the last 1MB of bytes + let slicedBytes = this.bytes.slice(start, end); + + // Convert the sliced bytes back to a string + let text = new TextDecoder().decode(slicedBytes); + + return text + } + + async getChunks(i: number): Promise { + i-- + if(i < this.totalChunks) { + const start = i * this.chunkSize; + const end = Math.min(start + this.chunkSize, this.bytes.length); + const chunk = await this.readChunk(start, end); + + return chunk + } + } + +} + interface IUploadResponse { result: Result attemp: number @@ -424,6 +498,8 @@ export class ChucksManager { needToCommit = true subscribeToUseCaseResponse: Function[] = [] + updateTotalPercentageTrigger = () => {} + getUploadPercentage() { return this.uploadPercentage } @@ -483,6 +559,7 @@ export class ChucksManager { setPercentage() { const percentage: number = this.calculatePercentage() console.log({percentage}) + this.updateTotalPercentageTrigger() this.uploadPercentage = percentage.toString()+"%" } diff --git a/src/app/shared/publication/view-publications/view-publications.page.html b/src/app/shared/publication/view-publications/view-publications.page.html index 34f8082b1..6463234c5 100644 --- a/src/app/shared/publication/view-publications/view-publications.page.html +++ b/src/app/shared/publication/view-publications/view-publications.page.html @@ -30,7 +30,7 @@ - + diff --git a/src/app/shared/publication/view-publications/view-publications.page.ts b/src/app/shared/publication/view-publications/view-publications.page.ts index e96921b77..695ebe2ca 100644 --- a/src/app/shared/publication/view-publications/view-publications.page.ts +++ b/src/app/shared/publication/view-publications/view-publications.page.ts @@ -17,6 +17,8 @@ import { AskModalPage } from 'src/app/modals/ask-modal/ask-modal.page'; import { checkFileTypeService } from 'src/app/services/checkFileType.service'; import { PublicationVideoManagerService } from "src/app/services/publication/publication-video-manager.service"; import { StopvideoService } from "src/app/services/stopvideo.service"; +import { PublicationHolderService } from 'src/app/services/publication/publication-holder.service' + @Component({ selector: 'app-view-publications', templateUrl: './view-publications.page.html', @@ -72,7 +74,8 @@ export class ViewPublicationsPage implements OnInit { public publicationFolderService: PublicationFolderService, public checkFileType: checkFileTypeService, private publicationVideoManagerService: PublicationVideoManagerService, - public StopvideoService: StopvideoService + public StopvideoService: StopvideoService, + public PublicationHolderService: PublicationHolderService ) { @@ -175,42 +178,9 @@ export class ViewPublicationsPage implements OnInit { this.showLoader = true; const folderId = this.folderId - try { - const publicationIds = await this.publications.GetPublicationsList(folderId).toPromise(); + await this.publicationFolderService.getPublicationsIds(folderId) - this.createPublicationList(folderId) - let loadLater = [] - for (let publicationId of publicationIds) { - - if (!this.publicationIsPresent(publicationId, folderId)) { - await this.loadPublication(publicationId, folderId) - - } else { - loadLater.push(publicationId) - } - } - - for (let publicationId of loadLater) { - await this.loadPublication(publicationId, folderId) - } - - - for (let localPublication of this.publicationFolderService.publicationList[folderId]) { - - const apiPublication = publicationIds.includes(localPublication.DocumentId) - if (!apiPublication) { - this.publicationFolderService.deletePost(folderId, localPublication.DocumentId) - } - } - - this.showLoader = false; - - this.storage.set(folderId, this.publicationFolderService.publicationList[folderId]); - - this.oldpublicationIds = publicationIds - } catch (error) { - this.showLoader = false; - } + this.showLoader = false; } @@ -231,31 +201,8 @@ export class ViewPublicationsPage implements OnInit { } async loadPublication(publicationId, folderId) { - let Publication = await this.publications.GetPublicationWithArrayOfFilesById(publicationId).toPromise(); - let publicationDetails: Publication = this.publicationPipe.itemList(Publication) - const findIndex = this.publicationFindIndex(publicationId, folderId) - const found = this.publicationIsPresent(publicationId, folderId) - - if (!found) { - this.publicationFolderService.publicationList[folderId].push(publicationDetails) - this.publicationFolderService.revertPublicationOrder(folderId) - } else { - - let a: any = Object.assign({},this.publicationFolderService.publicationList[folderId][findIndex]) - let b: any = Object.assign({}, publicationDetails) - - a.Files = a.Files.length - b.Files = b.Files.length - - if(JSON.stringify(a) != JSON.stringify(b)) { - - this.publicationFolderService.publicationList[folderId][findIndex] = publicationDetails - } else { - // console.log({publicationDetails}) - } - - } + await this.publicationFolderService.loadPublication(publicationId, folderId) } @@ -268,28 +215,36 @@ export class ViewPublicationsPage implements OnInit { async AddPublication(publicationType: any, folderId: any) { - if (window.innerWidth < 701) { - const modal = await this.modalController.create({ - component: NewPublicationPage, - componentProps: { + //if(this.PublicationHolderService.PublicationFormMV.length == 0) { + + if (window.innerWidth < 701) { + const modal = await this.modalController.create({ + component: NewPublicationPage, + componentProps: { + publicationType: publicationType, + folderId: folderId, + }, + cssClass: 'new-publication modal modal-desktop', + backdropDismiss: false + }); + + modal.onDidDismiss().then(() => { + this.doRefresh(event); + }); + + await modal.present(); + } else { + this.addNewPublication.emit({ publicationType: publicationType, - folderId: folderId, - }, - cssClass: 'new-publication modal modal-desktop', - backdropDismiss: false - }); + folderId: folderId + }) + } + // } else { + + // this.toastService._successMessage('já existe uma publicação a ser processado'); + //} - modal.onDidDismiss().then(() => { - this.doRefresh(event); - }); - await modal.present(); - } else { - this.addNewPublication.emit({ - publicationType: publicationType, - folderId: folderId - }) - } } @@ -378,24 +333,29 @@ export class ViewPublicationsPage implements OnInit { stopVideo() { - var videos = document.querySelectorAll('video'); - - // Pause each video - videos.forEach(function (video) { - video.pause(); - }) - try { + var videos = document.querySelectorAll('video'); - this.videoElements.forEach(videoElement => { - // You can access the native HTML video element using videoElement.nativeElement - const video: HTMLVideoElement = videoElement.nativeElement; + // Pause each video + videos.forEach(function (video) { + video.pause(); + }) - video.pause() - // Do something with each video element - // console.log(video); - }); - } catch (e) { + try { + + this.videoElements.forEach(videoElement => { + // You can access the native HTML video element using videoElement.nativeElement + const video: HTMLVideoElement = videoElement.nativeElement; + + video.pause() + // Do something with each video element + // console.log(video); + }); + } catch (e) { + + } + + } catch (error) { } diff --git a/src/environments/environment.prod.ts b/src/environments/environment.prod.ts index 1b55290ea..43c1647f5 100644 --- a/src/environments/environment.prod.ts +++ b/src/environments/environment.prod.ts @@ -1,7 +1,7 @@ import { Environment } from './../app/models/envarioment' import { environment as oaprProd } from './suport/oapr' -import { environment as doneITProd } from './suport/doneIt' - import { DevDev } from './suport/dev' +// import { environment as doneITProd } from './suport/doneIt' +import { DevDev } from './suport/dev' -export const environment: Environment = oaprProd; +export const environment: Environment = DevDev; diff --git a/src/environments/environment.ts b/src/environments/environment.ts index 983359e87..8982b9007 100644 --- a/src/environments/environment.ts +++ b/src/environments/environment.ts @@ -1,6 +1,6 @@ import { Environment } from './../app/models/envarioment' import { environment as oaprDev } from './suport/oapr' -import { doneITDev } from './suport/doneIt' +// import { doneITDev } from './suport/doneIt' import { DevDev } from './suport/dev'