Merge branch 'feature/viewer-attachment' of https://bitbucket.org/equilibriumito/gabinete-digital-fo into feature/viewer-attachment

This commit is contained in:
Equilibrium ITO
2024-03-26 14:32:32 +01:00
41 changed files with 3846 additions and 3606 deletions
@@ -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(() => {
+1 -11
View File
@@ -35,7 +35,6 @@ import { ChatMessageDebuggingPage } from 'src/app/shared/popover/chat-message-de
import { PermissionService } from 'src/app/services/permission.service';
import { FileValidatorService } from "src/app/services/file/file-validator.service"
import { ChangeDetectorRef } from '@angular/core';
import { saveAs } from 'file-saver';
const IMAGE_DIR = 'stored-images';
@@ -125,8 +124,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()
@@ -142,9 +140,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
@@ -162,11 +157,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}
changeDetector = () => {
console.log('run detection shared')
this.ChangeDetectorRef.detectChanges()
}
async ChatMessageDebuggingPage() {
@@ -33,7 +33,7 @@ export class ExpedientsPage implements OnInit {
listSubscription : {
delete(): void;
}
routerSubscription;
@@ -69,7 +69,7 @@ export class ExpedientsPage implements OnInit {
}
})
this.routerSubscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationStart &&
event.url.startsWith('/home/gabinete-digital?expedientes=true')) {
@@ -81,8 +81,8 @@ export class ExpedientsPage implements OnInit {
this.LoadList()
}
this.dynamicSearch();
}
@@ -91,7 +91,7 @@ export class ExpedientsPage implements OnInit {
this.listSubscription.delete()
this.routerSubscription?.unsubscribe();
}
reorderList(orderBy: string) {
this.ordinance = orderBy;
@@ -103,7 +103,7 @@ export class ExpedientsPage implements OnInit {
async dynamicSearch() {
if(this.showSearch && this.searchSubject) {
const list = this.expedientegbstore.list.filter((task) => {
let subject = task.Folio || task.Subject || task.workflowInstanceDataFields.Subject
subject = subject.toLowerCase();
@@ -143,7 +143,7 @@ export class ExpedientsPage implements OnInit {
this.skeletonLoader = true
this.processes.GetTaskListExpediente(false).subscribe(result => {
let taskslist = [];
this.skeletonLoader = false
@@ -152,7 +152,7 @@ export class ExpedientsPage implements OnInit {
taskslist = res.map((e) => this.expedienteTaskPipe.transform(e))
taskslist = this.sortService.sortDate(taskslist, 'CreateDate')
// this.addProcessTODb(taskslist);
taskslist = taskslist.filter(function(item) {
return item.activityInstanceName != 'Retificar Expediente'
})
+20 -3
View File
@@ -40,14 +40,23 @@
</div>
</div>
<div title="Perfil" class="div-profile cursor-pointer viewport-font-size " (click)="openProfile()">
<div title="Perfil" class="div-profile cursor-pointer viewport-font-size " >
<div *ngIf="PublicationHolderService.count != 0" style="color: black" style="display: flex;
color: black;
justify-content: center;
align-items: center;
" >
<span *ngIf="!PublicationHolderService.PublicationFormMV?.[0]?.retry">{{ PublicationHolderService.count }}%</span>
<span style="padding-right: 12px" *ngIf="PublicationHolderService.PublicationFormMV?.[0]?.retry" (click)="PublicationHolderService.PublicationFormMV?.[0]?.retryFunction()" ><ion-icon src="assets/images/retry-svgrepo-com.svg" > </ion-icon></span>
<span style="padding-right: 7px" *ngIf="PublicationHolderService.PublicationFormMV?.[0]?.retry" (click)="PublicationHolderService.remove(PublicationHolderService.PublicationFormMV?.[0]?.id)">X</span>
</div>
<!-- <div *ngIf="this.NotificationHolderService.notificationList.length > 0" class="icon-badge">{{NotificationHolderService.notificationList.length}}</div> -->
<!-- <ion-icon *ngIf="ThemeService.currentTheme == 'doneIt' " class="icon font-45-em" src='assets/images/theme/doneIt/icons-profile.svg'></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="icon font-45-em" src='assets/images/icons-profile.svg'></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="icon font-45-em" src='assets/images/theme/gov/icons-profile.svg'></ion-icon> -->
<div *ngIf="profilePicture == ''" class="profile-image">
<div (click)="openProfile()" *ngIf="profilePicture == ''" class="profile-image" >
<!-- <img *ngIf="loggeduser.RoleDescription == 'Presidente da República' " class="profile-image"
src='assets/images/presidente.png'>
<img *ngIf="loggeduser.RoleDescription == 'Ministro e Director do Gabinete do PR' " class="profile-image"
@@ -60,7 +69,7 @@
</div>
<div *ngIf="profilePicture != ''" class="profile-image">
<div (click)="openProfile()" *ngIf="profilePicture != ''" class="profile-image">
<img class="profile-image image-prety" src={{profilePicture}}>
</div>
@@ -164,6 +173,13 @@
</div>
<div class="header-btns d-flex">
<div *ngIf="PublicationHolderService.count != 0" style="color: black" >
<span *ngIf="!PublicationHolderService.PublicationFormMV?.[0]?.retry">{{ PublicationHolderService.count }}%</span>
<span style="padding-right: 12px" *ngIf="PublicationHolderService.PublicationFormMV?.[0]?.retry" (click)="PublicationHolderService.PublicationFormMV?.[0]?.retryFunction()" ><ion-icon src="assets/images/retry-svgrepo-com.svg" > </ion-icon></span>
<span style="padding-right: 7px" *ngIf="PublicationHolderService.PublicationFormMV?.[0]?.retry" (click)="PublicationHolderService.remove(PublicationHolderService.PublicationFormMV?.[0]?.id)">X</span>
</div>
<div title="Pesquisa" *ngIf="!hideSearchBtn" class="mr-20 d-flex align-center cursor-pointer">
<div style="padding-top: 5px;" (click)="openSearch();showSearch=true" *ngIf="!showSearch">
<ion-icon title="Perfil" *ngIf="ThemeService.currentTheme == 'doneIt' " class="font-45-rem"
@@ -241,3 +257,4 @@
</div>
<div [class.header-bottom-line]="ThemeService.currentTheme == 'gov'" style="height: 5px;"></div>
</div>
+1 -2
View File
@@ -86,8 +86,7 @@
}
.div-profile {
width: 40px;
height: 40px;
text-align: center;
background-color: transparent;
display: flex !important;
+8 -2
View File
@@ -17,7 +17,7 @@ import { NotificationsService } from 'src/app/services/notifications.service';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { NotificationHolderService } from 'src/app/store/notification-holder.service';
import { HeaderSettingsService } from "src/app/services/header-settings.service"
import { PublicationHolderService } from 'src/app/services/publication/publication-holder.service'
@Component({
selector: 'app-header',
templateUrl: './header.page.html',
@@ -53,7 +53,6 @@ export class HeaderPage implements OnInit {
}
}
constructor(
private router: Router,
private modalController: ModalController,
@@ -72,6 +71,7 @@ export class HeaderPage implements OnInit {
private attachmentService: AttachmentsService,
public NotificationHolderService: NotificationHolderService,
public HeaderSettingsService: HeaderSettingsService,
public PublicationHolderService: PublicationHolderService
) {
this.loggeduser = SessionStore.user;
router.events.subscribe((val) => {
@@ -89,6 +89,12 @@ export class HeaderPage implements OnInit {
this.notificationLengthData()
}); */
window['header-updateCount'] = () => {
this.updateCount()
}
}
updateCount = () => {
}
@@ -142,6 +142,7 @@ export class OptsExpedientePage implements OnInit {
const loader = this.toastService.loading()
this.attachmentsService.AddAttachment(body).subscribe((res)=> {
window['attachments-expediente-update']();
this.toastService._successMessage()
this.popoverController.dismiss()
}, (error) => {
@@ -16,7 +16,7 @@
<div *ngIf="publicationType!='1'" class="ion-item-container"
[class.input-error]="Form?.get('Subject')?.invalid && validateFrom ">
<ion-input autocomplete="on" autocorrect="on" spellcheck="true" [(ngModel)]="publicationFormMV.form.Title" name="title"
<ion-input autocomplete="on" autocorrect="on" spellcheck="true" [(ngModel)]="PublicationFromMvService.form.Title" name="title"
placeholder="Título*"></ion-input>
</div>
@@ -27,7 +27,7 @@
</div>
<div class="ion-textarea-class flex-grow-1"
[class.input-error]="Form?.get('Message')?.invalid && validateFrom ">
<ion-textarea autocomplete="on" autocorrect="on" spellcheck="true" [(ngModel)]="publicationFormMV.form.Message"
<ion-textarea autocomplete="on" autocorrect="on" spellcheck="true" [(ngModel)]="PublicationFromMvService.form.Message"
name="description" ngDefaultControl rows="12" cols="20" placeholder="Corpo de texto*"></ion-textarea>
</div>
</div>
@@ -40,12 +40,12 @@
<!-- Captured -->
<div *ngIf="publicationFormMV.form.Files.length > 0">
<div *ngIf="PublicationFromMvService.form.Files.length > 0">
<ion-label class="attached-title pb-10">Anexos</ion-label>
<div>
<div class="d-flex" >
<div *ngFor="let seleted of publicationFormMV.form.Files.slice(0, displayLimit), let i = index" lot="start" class="mr-10">
<div *ngFor="let seleted of PublicationFromMvService.form.Files.slice(0, displayLimit), let i = index" lot="start" class="mr-10">
<div>
@@ -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,143 +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()
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"
}
if(e.FileType == 'video' ) {
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("É 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() {
@@ -722,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() {
@@ -744,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')
@@ -792,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) {
@@ -834,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) {
@@ -1,9 +0,0 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PublicationFormMVService {
constructor() { }
}
@@ -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', () => {
@@ -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 = 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.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<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)
window['upload-header-remove-retry'](this.id);
const videosFilesToUploads = videosFiles.filter( e => e.FileType == "video" && e.toUpload)
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.');
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;
}
}
}
@@ -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<Result<true, IOUploadError >> {
@@ -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) {
@@ -240,25 +248,50 @@ export class PublicationFormMV {
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) {
const fileBlob = PublicationAttachmentEntity.blobFile;
const fileChunks = new Chunks({chunkSize: 400 })
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<true, IOUploadError>
if( PublicationAttachmentEntity.chucksManager.isUploading == false) {
if( PublicationAttachmentEntity.chucksManager.isUploading == false && PublicationAttachmentEntity.chucksManager.doneUpload == false) {
do {
attemp++
@@ -276,20 +309,16 @@ export class PublicationFormMV {
resolve(false)
} else {
PublicationAttachmentEntity.chucksManager.doneChunkUpload()
const mergeRequest = await this.ObjectMergeNotification.socket.commit(PublicationAttachmentEntity.chucksManager.path)
if(mergeRequest.isOk()) {
PublicationAttachmentEntity.chucksManager.contentSetReady()
resolve(true)
} else {
resolve(false)
}
return await resolve(this.commit(PublicationAttachmentEntity))
}
} else {
} else if ( PublicationAttachmentEntity.chucksManager.contentReady == false) {
console.log("try to send again")
return await resolve(this.commit(PublicationAttachmentEntity))
} else {
console.log('already uploading')
}
})
@@ -303,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<any>[] = []
@@ -320,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.');
}
@@ -336,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;
}
}
@@ -397,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<string> {
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<any, Error>
attemp: number
@@ -413,8 +495,11 @@ export class ChucksManager {
contentReady = false
manualRetry = false
isUploading = false
needToCommit = true
subscribeToUseCaseResponse: Function[] = []
updateTotalPercentageTrigger = () => {}
getUploadPercentage() {
return this.uploadPercentage
}
@@ -474,6 +559,7 @@ export class ChucksManager {
setPercentage() {
const percentage: number = this.calculatePercentage()
console.log({percentage})
this.updateTotalPercentageTrigger()
this.uploadPercentage = percentage.toString()+"%"
}
@@ -531,6 +617,10 @@ export class ChucksManager {
this.onSetLastChunk.forEach(callback => callback());
}
doneCommit() {
this.needToCommit = false
}
contentSetReady() {
this.merging = false
this.contentReady = true
@@ -30,7 +30,7 @@
<ion-content>
<ion-refresher name="refresher" slot="fixed" (ionRefresh)="doRefresh($event)">
<ion-progress-bar type="indeterminate" *ngIf="showLoader"></ion-progress-bar>
<ion-progress-bar type="indeterminate" *ngIf="showLoader || publicationFolderService.showLoader"></ion-progress-bar>
<ion-refresher-content>
</ion-refresher-content>
</ion-refresher>
@@ -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
) {
@@ -129,6 +132,10 @@ export class ViewPublicationsPage implements OnInit {
this.stopVideo();
setTimeout(()=> {
this.doRefresh({})
}, 1500)
}
@@ -171,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;
}
@@ -227,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)
}
@@ -264,29 +215,37 @@ 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
});
modal.onDidDismiss().then(() => {
this.doRefresh(event);
});
await modal.present();
folderId: folderId
})
}
} else {
this.addNewPublication.emit({
publicationType: publicationType,
folderId: folderId
})
this.toastService._successMessage('já existe uma publicação a ser processado');
}
}
async openEditPublication(folderId?: any) {
@@ -374,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) {
}