diff --git a/gabinete-digital-fo.code-workspace b/gabinete-digital-fo.code-workspace index 2730d9669..f1b39c052 100644 --- a/gabinete-digital-fo.code-workspace +++ b/gabinete-digital-fo.code-workspace @@ -14,9 +14,6 @@ }, { "path": "../sih" - }, - { - "path": "../Ionic-Video-Capture-Play-main" } ], "settings": { diff --git a/package-lock.json b/package-lock.json index a0d74e455..b401e08dd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -48,7 +48,9 @@ "@capacitor/push-notifications": "^5.1.0", "@capacitor/share": "^4.1.0", "@capacitor/storage": "^1.2.5", - "@capawesome/capacitor-file-picker": "^5.1.1", + "@capawesome/capacitor-file-picker": "^5.3.0", + "@ffmpeg/core": "^0.12.6", + "@ffmpeg/ffmpeg": "^0.12.10", "@fortawesome/angular-fontawesome": "^0.9.0", "@fortawesome/fontawesome-free": "^5.15.3", "@fortawesome/fontawesome-svg-core": "^1.2.35", @@ -153,6 +155,7 @@ "lite-server": "^2.6.1", "minisearch": "^6.0.1", "moment": "^2.29.3", + "mux.js": "^6.3.0", "neverthrow": "^6.1.0", "ng-lazyload-image": "^9.1.2", "ng2-pdf-viewer": "^3.0.8", @@ -3615,7 +3618,6 @@ "version": "7.14.8", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.14.8.tgz", "integrity": "sha512-twj3L8Og5SaCRCErB4x4ajbvBIVV77CGeFglHpeg5WC5FF8TZzBWXtTJ4MqaD9QszLYTtr+IsaAL2rEUevb+eg==", - "dev": true, "dependencies": { "regenerator-runtime": "^0.13.4" }, @@ -4018,9 +4020,9 @@ } }, "node_modules/@capawesome/capacitor-file-picker": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@capawesome/capacitor-file-picker/-/capacitor-file-picker-5.1.1.tgz", - "integrity": "sha512-VtWV/er8Kux5Bbb0BtRneAaL8aj7zKoSPSR5sn3QlVBccete+CX+nH3scg6JKrogoitNP35PS33LIoaz9WVZiA==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@capawesome/capacitor-file-picker/-/capacitor-file-picker-5.3.0.tgz", + "integrity": "sha512-r+cfD+9FCBXMYtckSovgi7WoMWT5cxzNDaH3SDNuiORiyQklOl+7DExfhW00p1DqsDR+f50nADk/NBb4IsGVYg==", "funding": [ { "type": "github", @@ -4231,6 +4233,33 @@ "node": ">=10.0.0" } }, + "node_modules/@ffmpeg/core": { + "version": "0.12.6", + "resolved": "https://registry.npmjs.org/@ffmpeg/core/-/core-0.12.6.tgz", + "integrity": "sha512-PrjWBTfGn2WVn9T7wGnzfFwChbqWeZc7tM9vvJZVRadYFUDakfzy7W0LpYC0cvvK0xT82qlBsk38lQhJ/Hps5A==", + "engines": { + "node": ">=16.x" + } + }, + "node_modules/@ffmpeg/ffmpeg": { + "version": "0.12.10", + "resolved": "https://registry.npmjs.org/@ffmpeg/ffmpeg/-/ffmpeg-0.12.10.tgz", + "integrity": "sha512-lVtk8PW8e+NUzGZhPTWj2P1J4/NyuCrbDD3O9IGpSeLYtUZKBqZO8CNj1WYGghep/MXoM8e1qVY1GztTkf8YYQ==", + "dependencies": { + "@ffmpeg/types": "^0.12.2" + }, + "engines": { + "node": ">=18.x" + } + }, + "node_modules/@ffmpeg/types": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/@ffmpeg/types/-/types-0.12.2.tgz", + "integrity": "sha512-NJtxwPoLb60/z1Klv0ueshguWQ/7mNm106qdHkB4HL49LXszjhjCCiL+ldHJGQ9ai2Igx0s4F24ghigy//ERdA==", + "engines": { + "node": ">=16.x" + } + }, "node_modules/@firebase/analytics": { "version": "0.6.18", "resolved": "https://registry.npmjs.org/@firebase/analytics/-/analytics-0.6.18.tgz", @@ -26817,6 +26846,22 @@ "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" }, + "node_modules/mux.js": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/mux.js/-/mux.js-6.3.0.tgz", + "integrity": "sha512-/QTkbSAP2+w1nxV+qTcumSDN5PA98P0tjrADijIzQHe85oBK3Akhy9AHlH0ne/GombLMz1rLyvVsmrgRxoPDrQ==", + "dependencies": { + "@babel/runtime": "^7.11.2", + "global": "^4.4.0" + }, + "bin": { + "muxjs-transmux": "bin/transmux.js" + }, + "engines": { + "node": ">=8", + "npm": ">=5" + } + }, "node_modules/nan": { "version": "2.17.0", "resolved": "https://registry.npmjs.org/nan/-/nan-2.17.0.tgz", @@ -46185,7 +46230,6 @@ "version": "7.14.8", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.14.8.tgz", "integrity": "sha512-twj3L8Og5SaCRCErB4x4ajbvBIVV77CGeFglHpeg5WC5FF8TZzBWXtTJ4MqaD9QszLYTtr+IsaAL2rEUevb+eg==", - "dev": true, "requires": { "regenerator-runtime": "^0.13.4" } @@ -46494,9 +46538,9 @@ "requires": {} }, "@capawesome/capacitor-file-picker": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@capawesome/capacitor-file-picker/-/capacitor-file-picker-5.1.1.tgz", - "integrity": "sha512-VtWV/er8Kux5Bbb0BtRneAaL8aj7zKoSPSR5sn3QlVBccete+CX+nH3scg6JKrogoitNP35PS33LIoaz9WVZiA==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@capawesome/capacitor-file-picker/-/capacitor-file-picker-5.3.0.tgz", + "integrity": "sha512-r+cfD+9FCBXMYtckSovgi7WoMWT5cxzNDaH3SDNuiORiyQklOl+7DExfhW00p1DqsDR+f50nADk/NBb4IsGVYg==", "requires": {} }, "@cnakazawa/watch": { @@ -46659,6 +46703,24 @@ "integrity": "sha512-Fxt+AfXgjMoin2maPIYzFZnQjAXjAL0PHscM5pRTtatFqB+vZxAM9tLp2Optnuw3QOQC40jTNeGYFOMvyf7v9g==", "dev": true }, + "@ffmpeg/core": { + "version": "0.12.6", + "resolved": "https://registry.npmjs.org/@ffmpeg/core/-/core-0.12.6.tgz", + "integrity": "sha512-PrjWBTfGn2WVn9T7wGnzfFwChbqWeZc7tM9vvJZVRadYFUDakfzy7W0LpYC0cvvK0xT82qlBsk38lQhJ/Hps5A==" + }, + "@ffmpeg/ffmpeg": { + "version": "0.12.10", + "resolved": "https://registry.npmjs.org/@ffmpeg/ffmpeg/-/ffmpeg-0.12.10.tgz", + "integrity": "sha512-lVtk8PW8e+NUzGZhPTWj2P1J4/NyuCrbDD3O9IGpSeLYtUZKBqZO8CNj1WYGghep/MXoM8e1qVY1GztTkf8YYQ==", + "requires": { + "@ffmpeg/types": "^0.12.2" + } + }, + "@ffmpeg/types": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/@ffmpeg/types/-/types-0.12.2.tgz", + "integrity": "sha512-NJtxwPoLb60/z1Klv0ueshguWQ/7mNm106qdHkB4HL49LXszjhjCCiL+ldHJGQ9ai2Igx0s4F24ghigy//ERdA==" + }, "@firebase/analytics": { "version": "0.6.18", "resolved": "https://registry.npmjs.org/@firebase/analytics/-/analytics-0.6.18.tgz", @@ -64261,6 +64323,15 @@ "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" }, + "mux.js": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/mux.js/-/mux.js-6.3.0.tgz", + "integrity": "sha512-/QTkbSAP2+w1nxV+qTcumSDN5PA98P0tjrADijIzQHe85oBK3Akhy9AHlH0ne/GombLMz1rLyvVsmrgRxoPDrQ==", + "requires": { + "@babel/runtime": "^7.11.2", + "global": "^4.4.0" + } + }, "nan": { "version": "2.17.0", "resolved": "https://registry.npmjs.org/nan/-/nan-2.17.0.tgz", diff --git a/src/app/services/socket-connection-mcr.service.ts b/src/app/services/socket-connection-mcr.service.ts index 57002ee8b..d885b7895 100644 --- a/src/app/services/socket-connection-mcr.service.ts +++ b/src/app/services/socket-connection-mcr.service.ts @@ -14,9 +14,9 @@ export class SocketConnectionMCRService { // private onDisconnect: Function[] = [] // private onConnect: Function[] = [] - // constructor(private http: HttpClient,) { - // window["http"] = this.http - // } + constructor(private http: HttpClient, private _CMAPIService: CMAPIService) { + window["http"] = this.http + } // connect() { @@ -67,137 +67,52 @@ export class SocketConnectionMCRService { } -// class ReconnectingWebSocketSignalR { +class ReconnectingWebSocketSignalR { -// private connection: any -// isOpen: boolean = false -// private callbacks: Function[] = [] -// private onDisconnect: Function[] = [] -// private onConnect: Function[] = [] -// private stop = true - -// constructor() {} - -// connect() { -// console.log("try to connect=================================") -// this.stop = false - -// this.connection = new signalR.HubConnectionBuilder() -// .withUrl("https://gdcmapi-dev.dyndns.info/FileHub", { -// transport: signalR.HttpTransportType.LongPolling, -// accessTokenFactory: () => SessionStore.user.Authorization -// }).configureLogging(signalR.LogLevel.Information) -// .build(); - - -// this.connection.start() -// .then(() => { -// this.isOpen = true; -// console.log('WebSocket connection established'); - - -// this.onConnect.forEach(callback => callback()); -// }) -// .catch((error) => { -// console.error("Error starting SignalR connection:", error); -// }); - - -// this.connection.on("ReceiveMessage", (message) => { -// const data: any = JSON.parse(message) -// console.log("ReceiveMessage", data) -// this.callbacks.forEach(callback => callback(data)); -// }) - -// this.connection.onclose((error) => { -// console.log('WebSocket connection closed..'); -// this.isOpen = false; -// this.onDisconnect.forEach(callback => callback()); -// // Attempt to reconnect after a delay -// if(this.stop == false) { -// setTimeout(() => { -// this.connect(); -// }, 1000); // Adjust the delay as needed -// } - -// }); -// } - -// disconnect() { -// this.stop = true -// if(this.isOpen == true) { -// this.connection.stop() -// .then(() => { -// console.log('WebSocket connection was closed by client'); -// this.isOpen = false; -// this.onDisconnect.forEach(callback => callback()); -// console.log("SignalR connection stopped."); -// }) -// .catch((error) => { -// console.error("Error stopping SignalR connection by client:", error); -// }); -// } -// } - -// subscribe(callback) { -// this.callbacks.push(callback); -// } - -// unsubscribe(callback) { -// this.callbacks = this.callbacks.filter(cb => cb !== callback); -// } - -// onDisconnectCallback(callback) { -// this.onDisconnect.push(callback) -// } -// onConnectCallback(callback) { -// this.onConnect.push(callback) -// } -// } - -interface socketResponse { - - index: string - Guid: string - IsCompleted: Boolean -} -class ReconnectingWebSocket { - - private url: string - private socket - isOpen: boolean + private connection: any + isOpen: boolean = false private callbacks: Function[] = [] private onDisconnect: Function[] = [] private onConnect: Function[] = [] + private whenConnected: Function[] = [] private stop = true - http: HttpClient = window["http"] - constructor(url) { - this.url = url; - this.socket = null; - this.isOpen = false; - this.connect(); - } + constructor() {} connect() { - this.socket = new WebSocket(this.url); + console.log("try to connect=================================") + this.stop = false - this.socket.addEventListener('open', (event) => { + this.connection = new signalR.HubConnectionBuilder() + .withUrl("https://gdcmapi-dev.dyndns.info/FileHub", { + transport: signalR.HttpTransportType.LongPolling, + accessTokenFactory: () => SessionStore.user.Authorization + }).configureLogging(signalR.LogLevel.Information) + .build(); + + + this.connection.start() + .then(() => { this.isOpen = true; console.log('WebSocket connection established'); - // Example: Send a message to the server - this.socket.send('Hello, WebSocket Server!'); + this.onConnect.forEach(callback => callback()); + this.whenConnected.forEach(callback => callback()) + }) + .catch((error) => { + console.error("Error starting SignalR connection:", error); }); - this.socket.addEventListener('message', (event) => { - const data: socketResponse = JSON.parse(event.data) + + this.connection.on("ReceiveMessage", (message) => { + const data: any = JSON.parse(message) + console.log("ReceiveMessage", data) this.callbacks.forEach(callback => callback(data)); - }); + }) - this.socket.addEventListener('close', (event) => { - console.log('WebSocket connection closed'); + this.connection.onclose((error) => { + console.log('WebSocket connection closed..'); this.isOpen = false; this.onDisconnect.forEach(callback => callback()); // Attempt to reconnect after a delay @@ -206,22 +121,27 @@ class ReconnectingWebSocket { this.connect(); }, 1000); // Adjust the delay as needed } + }); } - send(message) { - if (this.isOpen) { - this.socket.send(message); - } else { - console.error('WebSocket connection is not open. Unable to send message.'); - } + commit(path) { + this.connection.invoke("CommitUpload", path).catch(err => console.error(err.toString())); } disconnect() { this.stop = true - if (this.isOpen) { - this.isOpen = false; - this.socket.close(); + if(this.isOpen == true) { + this.connection.stop() + .then(() => { + console.log('WebSocket connection was closed by client'); + this.isOpen = false; + this.onDisconnect.forEach(callback => callback()); + console.log("SignalR connection stopped."); + }) + .catch((error) => { + console.error("Error stopping SignalR connection by client:", error); + }); } } @@ -239,94 +159,116 @@ class ReconnectingWebSocket { onConnectCallback(callback) { this.onConnect.push(callback) } -} - -export class ObjectMergeNotification{ - - socket = new ReconnectingWebSocket('ws://localhost:3002'); - callbacks: {[GUID: string]: Function} = {} - runWatch = true - CMAPIService: CMAPIService = window["CMAPIAPIRepository"] - watchCount = 0 - - constructor() { - this.socket.onDisconnectCallback(()=> { - console.log("run watch") - this.runWatch = true - this.watch() - }) - - this.socket.onConnectCallback(()=> { - console.log("open trigger") - 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.watch() - } - - async watch() { - - this.watchCount = 0; - - if(this.runWatch) { - setTimeout(async () => { - for(const [key, funx] of Object.entries(this.callbacks)) { - - const request = await this.CMAPIService.getVideoHeader(key) - - if(request.isOk()) { - funx() - delete this.callbacks[key] - } - } - - this.watchCount++ - if(this.watchCount <= 15) { - this.watch() - } else { - this.runWatch = false - } - - }, 1000) - + registerWhenConnected(f: Function) { + if(this.isOpen) { + f(); } else { - console.log("end loop============================") + this.whenConnected.push(f); } - } - close() { - this.socket.disconnect(); - this.watchCount = 0; - this.runWatch = false } - - subscribe(GUID, callback:Function) { - this.callbacks[GUID] = callback; - } - - unsubscribe(GUID) { - delete this.callbacks[GUID] - } - } +interface socketResponse { + + index: string + Guid: string + IsCompleted: Boolean +} +// class ReconnectingWebSocket { + +// private url: string +// private socket +// isOpen: boolean +// private callbacks: Function[] = [] +// private onDisconnect: Function[] = [] +// private onConnect: Function[] = [] +// private whenConnected: Function[] = [] +// private stop = true +// http: HttpClient = window["http"] + +// constructor(url) { +// this.url = url; +// this.socket = null; +// this.isOpen = false; +// } + +// connect() { +// this.socket = new WebSocket(this.url); + +// this.socket.addEventListener('open', (event) => { +// this.isOpen = true; +// console.log('WebSocket connection established'); + +// // Example: Send a message to the server +// this.socket.send('Hello, WebSocket Server!'); +// this.onConnect.forEach(callback => callback()); +// this.whenConnected.forEach(callback => callback()) +// }); + +// this.socket.addEventListener('message', (event) => { +// const data: socketResponse = JSON.parse(event.data) +// this.callbacks.forEach(callback => callback(data)); +// }); + +// this.socket.addEventListener('close', (event) => { +// console.log('WebSocket connection closed'); +// this.isOpen = false; +// this.onDisconnect.forEach(callback => callback()); +// // Attempt to reconnect after a delay +// if(this.stop == false) { +// setTimeout(() => { +// this.connect(); +// }, 1000); // Adjust the delay as needed +// } +// }); +// } + +// send(message) { +// if (this.isOpen) { +// this.socket.send(message); +// } else { +// console.error('WebSocket connection is not open. Unable to send message.'); +// } +// } + +// disconnect() { +// this.stop = true +// if (this.isOpen) { +// this.isOpen = false; +// this.socket.close(); +// } +// } + +// subscribe(callback) { +// this.callbacks.push(callback); +// } + +// unsubscribe(callback) { +// this.callbacks = this.callbacks.filter(cb => cb !== callback); +// } + +// onDisconnectCallback(callback) { +// this.onDisconnect.push(callback) +// } +// onConnectCallback(callback) { +// this.onConnect.push(callback) +// } + +// registerWhenConnected(f: Function) { +// if(this.isOpen) { +// f(); +// } else { +// this.whenConnected.push(f); +// } + +// } +// } // export class ObjectMergeNotification{ -// socket = new ReconnectingWebSocketSignalR() +// socket = new ReconnectingWebSocket('ws://localhost:3002'); // callbacks: {[GUID: string]: Function} = {} // runWatch = true // CMAPIService: CMAPIService = window["CMAPIAPIRepository"] @@ -340,15 +282,14 @@ export class ObjectMergeNotification{ // }) // this.socket.onConnectCallback(()=> { - // console.log("open trigger") // this.runWatch = false // }) - + // this.socket.subscribe((data: socketResponse) => { // if(data.IsCompleted == true) { // console.log("==================!!!====================") -// try { +// try { // this.callbacks[data.Guid](data) // delete this.callbacks[data.Guid] // } catch (error) {} @@ -357,15 +298,11 @@ export class ObjectMergeNotification{ // } // }) -// this.socket.connect(); // this.watch() // } - -// close() { -// this.socket.disconnect(); -// this.watchCount = 0; -// this.runWatch = false +// connect() { +// this.socket.connect() // } // async watch() { @@ -386,11 +323,11 @@ export class ObjectMergeNotification{ // this.watchCount++ // if(this.watchCount <= 15) { -// this.watch() +// this.watch() // } else { // this.runWatch = false // } - + // }, 1000) @@ -399,6 +336,12 @@ export class ObjectMergeNotification{ // } // } +// close() { +// this.socket.disconnect(); +// this.watchCount = 0; +// this.runWatch = false +// } + // subscribe(GUID, callback:Function) { // this.callbacks[GUID] = callback; // } @@ -408,3 +351,92 @@ export class ObjectMergeNotification{ // } // } + + +export class ObjectMergeNotification{ + + socket = new ReconnectingWebSocketSignalR() + callbacks: {[GUID: string]: Function} = {} + runWatch = true + CMAPIService: CMAPIService = window["CMAPIAPIRepository"] + watchCount = 0 + + constructor() { + this.socket.onDisconnectCallback(()=> { + console.log("run watch") + this.runWatch = true + this.watch() + }) + + this.socket.onConnectCallback(()=> { + + console.log("open trigger") + 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.connect(); + this.watch() + } + + connect() { + this.socket.connect(); + } + + close() { + this.socket.disconnect(); + this.watchCount = 0; + this.runWatch = false + } + + async watch() { + + // this.watchCount = 0; + + // if(this.runWatch) { + // setTimeout(async () => { + // for(const [key, funx] of Object.entries(this.callbacks)) { + + // const request = await this.CMAPIService.getVideoHeader(key) + + // if(request.isOk()) { + // funx() + // delete this.callbacks[key] + // } + // } + + // this.watchCount++ + // if(this.watchCount <= 15) { + // this.watch() + // } else { + // this.runWatch = false + // } + + // }, 1000) + + + // } else { + // console.log("end loop============================") + // } + } + + subscribe(GUID, callback:Function) { + this.callbacks[GUID] = callback; + } + + unsubscribe(GUID) { + delete this.callbacks[GUID] + } + +} diff --git a/src/app/shared/API/middleware/middleware-service.service.ts b/src/app/shared/API/middleware/middleware-service.service.ts index 084a5c1d8..a82bd7cf6 100644 --- a/src/app/shared/API/middleware/middleware-service.service.ts +++ b/src/app/shared/API/middleware/middleware-service.service.ts @@ -23,7 +23,7 @@ export class MiddlewareServiceService { window["MiddlewareServiceService"] = this } - refreshToken(refreshToken: string){ + refreshToken(refreshToken: string) { const data = { refreshToken: refreshToken } @@ -186,15 +186,13 @@ export class MiddlewareServiceService { const headers = new HttpHeaders(); headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); - const geturl = 'http://localhost:3001/FileHub'; - // const geturl = environment.apiURL + 'Tasks/DelegateTask'; - // const geturl = environment.apiPCURL + 'FileContent'; + // const geturl = 'http://localhost:3001/FileHub'; + const geturl = environment.apiPCURL + 'FileContent/UploadFile'; let options = { headers: headers }; - const formData = new FormData(); formData.append("blobFile", blobFile); @@ -208,6 +206,15 @@ export class MiddlewareServiceService { return this.http.post(`${geturl}`, formData, options) } + CMAPIRequestUpload() { + const geturl = environment.apiPCURL + 'FileContent/RequestUpload'; + return this.http.get(`${geturl}`) + } + + CMAPIUploadStatus() { + const geturl = environment.apiPCURL + 'FileContent/UploadStatus'; + return this.http.get(`${geturl}`) + } tryToReachTheServer() { diff --git a/src/app/shared/publication/new-publication/new-publication.page.html b/src/app/shared/publication/new-publication/new-publication.page.html index 8dba39bdf..6fa3b82a5 100644 --- a/src/app/shared/publication/new-publication/new-publication.page.html +++ b/src/app/shared/publication/new-publication/new-publication.page.html @@ -56,33 +56,35 @@ -
+ + + + - + + +
- -
- - -

mais {{ seletedContent.length - displayLimit }}

-

{{capturedImageTitle}}

@@ -144,6 +146,10 @@
+ + + + 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 f377503d4..bb6c32fd5 100644 --- a/src/app/shared/publication/new-publication/new-publication.page.ts +++ b/src/app/shared/publication/new-publication/new-publication.page.ts @@ -265,9 +265,9 @@ export class NewPublicationPage implements OnInit { ).then(r => r.blob()); */ /* console.log(await blob.arrayBuffer()); - - - + + + console.log("base64 :data:video/mp4;base64,",this.arrayBufferToBase64(await blob.arrayBuffer())) */ this.convertBlobToBase64(blobFile.blob).then((value: string) => { @@ -445,7 +445,6 @@ export class NewPublicationPage implements OnInit { Files: this.seletedContent, } - this.publicationFormMV.setDataToFrom(this.publication) const upload = await this.publicationFormMV.uploadVideosFiles() @@ -455,10 +454,12 @@ export class NewPublicationPage implements OnInit { e.OriginalFileName = e.chucksManager.path.replace(".mp4", "") e.FileExtension = "mp4" } + this.publicationFormMV.ObjectMergeNotification.socket.commit(e.chucksManager.path) return e }) + console.log("this.publication.Files", this.publication.Files) } @@ -480,7 +481,7 @@ export class NewPublicationPage implements OnInit { this.httpErroHandle.httpStatusHandle(error) if (error.status == 404) { this.PublicationFolderService.deletePost(this.publication.ProcessId, this.publication.DocumentId) - this.goBack(); + //this.goBack(); } } finally { loader.remove() @@ -507,7 +508,6 @@ export class NewPublicationPage implements OnInit { Files: this.seletedContent, } - this.publicationFormMV.setDataToFrom(this.publication) const upload = await this.publicationFormMV.uploadVideosFiles() @@ -519,49 +519,60 @@ export class NewPublicationPage implements OnInit { e.Base64 = "" } + alert("commit") + this.publicationFormMV.ObjectMergeNotification.socket.commit(e.chucksManager.path) + return e }) - } - - this.publication.Files = this.publication.Files.map( (e:PublicationAttachmentEntity) => ({ - FileBase64: e.Base64, - FileExtension: e.FileExtension, - OriginalFileName: e.OriginalFileName || 'foto' - })) - const loader = this.toastService.loading() - try { + this.publication.Files = this.publication.Files.map( (e:PublicationAttachmentEntity) => ({ + FileBase64: e.Base64, + FileExtension: e.FileExtension, + OriginalFileName: e.OriginalFileName || 'foto' + })) - await this.publications.CreatePublication(this.publication.ProcessId, this.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') + + + const loader = this.toastService.loading() + + try { + + await this.publications.CreatePublication(this.publication.ProcessId, this.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() } - 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.publicationFormMV.ObjectMergeNotification.close() } ngOnDestroy() { - this.publicationFormMV.ObjectMergeNotification.close() + // this.publicationFormMV.ObjectMergeNotification.close() } close() { diff --git a/src/app/shared/publication/upload/upload-streaming.service.ts b/src/app/shared/publication/upload/upload-streaming.service.ts index 34bd620e2..211df04c9 100644 --- a/src/app/shared/publication/upload/upload-streaming.service.ts +++ b/src/app/shared/publication/upload/upload-streaming.service.ts @@ -2,6 +2,17 @@ import { Injectable } from '@angular/core'; 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" + +const objectMergeNotification = new ObjectMergeNotification() + +export enum UploadError { + noConnection = 'noConnection', + slow = 'slow' +} + +export type IOUploadError = "noConnection" | "slow" + + @Injectable({ providedIn: 'root' }) @@ -9,112 +20,85 @@ export class UploadStreamingService { constructor( private CMAPIService: CMAPIService,) { } } - class UploadFileUseCase { CMAPIService: CMAPIService = window["CMAPIAPIRepository"] constructor() {} - async execute(PublicationAttachmentEntity: PublicationAttachmentEntity): Promise> { + async execute(PublicationAttachmentEntity: PublicationAttachmentEntity): Promise> { return new Promise(async (resolve, reject) => { - PublicationAttachmentEntity.chucksManager.clearManualRetry() - let path: string; const length = PublicationAttachmentEntity.chucksManager.chunks.totalChunks.toString() const readAndUploadChunk = async(index: number) => { - const chunk = await PublicationAttachmentEntity.chucksManager.chunks.getChunks(index) - const blob = new Blob([chunk]); - const blobFile = new File([blob], "test.mp4", { type: blob.type }); + const base64 = await PublicationAttachmentEntity.chucksManager.chunks.getChunks(index) - return this.CMAPIService.FileContent({length, path: PublicationAttachmentEntity.chucksManager.path, index, blobFile}) - } - if(!PublicationAttachmentEntity.chucksManager.hasPath()) { - const initIndex = 1 + if(index == 2) { + const base1 = await PublicationAttachmentEntity.chucksManager.chunks.getChunks(2) - const uploadRequest = await readAndUploadChunk(initIndex) + // Get the video element from the DOM + const videoElement: any = document.getElementById("yourVideoElementId"); - if(uploadRequest.isOk()) { + // Set the src attribute of the video element to the blob URL + videoElement.src = "data:video/mp4;base64,"+ base1 + base64 ; - path = uploadRequest.value.data - - PublicationAttachmentEntity.chucksManager.setPath(path) - PublicationAttachmentEntity.chucksManager.setResponse(initIndex, uploadRequest) - alert("passs") - } else { - alert("erro dfsdfsdfsdr") - PublicationAttachmentEntity.chucksManager.clearUploading() - PublicationAttachmentEntity.chucksManager.setManualRetry() - return reject(err(PublicationAttachmentEntity)) + // Optionally, you can also set other attributes or play the video + videoElement.controls = true; // Add controls for play, pause, etc. + videoElement.play(); // Auto-play the vid } + + const uploadRequest = this.CMAPIService.FileContent({length, path: PublicationAttachmentEntity.chucksManager.path, index, blobFile: base64}) + + uploadRequest.then((uploadRequest) => { + if(uploadRequest.isOk()) { + PublicationAttachmentEntity.chucksManager.setResponse(index, uploadRequest) + } + }) + + return uploadRequest; } + // if(!PublicationAttachmentEntity.chucksManager.hasPath()) { + // const guidRequest = await this.CMAPIService.RequestUpload() + + // if(guidRequest.isOk()) { + // path = guidRequest.value+".mp4" + // PublicationAttachmentEntity.chucksManager.setPath(path) + // } else { + // const pingRequest = await this.CMAPIService.ping() + // if( pingRequest.isErr()) { + // return resolve(err(UploadError.noConnection)) + // } else { + // return resolve(err(UploadError.slow)) + // } + // } + // } + const allRequest: Promise[] = [] let connection = true + let errorMessage: UploadError.noConnection | UploadError.slow - for (let index = 2; ( (index <= PublicationAttachmentEntity.chucksManager.chunks.totalChunks -1) && connection ); index++) { + for (let index = 1; ( (index <= PublicationAttachmentEntity.chucksManager.chunks.totalChunks) ); index++) { const needUpload = PublicationAttachmentEntity.chucksManager.needToUploadChunkIndex(index) if(needUpload) { const request = readAndUploadChunk(index).then(async(uploadRequest) => { - if(uploadRequest.isErr()) { - const pingRequest = await this.CMAPIService.ping() - if( pingRequest.isErr()) { - connection = false - return reject(err(PublicationAttachmentEntity)) - } - } else { - PublicationAttachmentEntity.chucksManager.setResponse(index, uploadRequest) - } + }) allRequest.push(request) - - // const request = readAndUploadChunk(index) - // const uploadRequest = await request - - // allRequest.push(request) - // if(uploadRequest.isErr()) { - // const pingRequest = await this.CMAPIService.ping() - // if( pingRequest.isErr()) { - // reject(err(PublicationAttachmentEntity)) - // } - // } else { - // PublicationAttachmentEntity.chucksManager.setResponse(index, uploadRequest) - // } } } + await Promise.all(allRequest) + if(!connection) { - PublicationAttachmentEntity.chucksManager.clearUploading() - PublicationAttachmentEntity.chucksManager.setManualRetry() - return reject(err(PublicationAttachmentEntity)) - } else if (PublicationAttachmentEntity.chucksManager.chunks.totalChunks != 1) { - await Promise.all(allRequest) - - const uploadRequest = await readAndUploadChunk(PublicationAttachmentEntity.chucksManager.chunks.totalChunks) - if(uploadRequest.isErr()) { - const pingRequest = await this.CMAPIService.ping() - if( pingRequest.isErr()) { - } - - PublicationAttachmentEntity.chucksManager.clearUploading() - PublicationAttachmentEntity.chucksManager.setManualRetry() - return reject(err(PublicationAttachmentEntity)) - } else { - PublicationAttachmentEntity.chucksManager.setResponse(PublicationAttachmentEntity.chucksManager.chunks.totalChunks, uploadRequest) - PublicationAttachmentEntity.chucksManager.doneChunkUpload() - return resolve(ok(PublicationAttachmentEntity)) - } - + return resolve(err(errorMessage)) } else { - - PublicationAttachmentEntity.chucksManager.doneChunkUpload() - return resolve(ok(PublicationAttachmentEntity)) + return resolve(ok(true)) } - }) } } @@ -215,7 +199,11 @@ export class PublicationFormMV { private UploadFileUseCase = new UploadFileUseCase() private form = new PublicationFormModel() - ObjectMergeNotification = new ObjectMergeNotification() + ObjectMergeNotification = objectMergeNotification + + constructor() { + this.ObjectMergeNotification.connect(); + } setDataToFrom(data: IPublicationFormModelEntity) { this.form.setData(data) @@ -231,12 +219,14 @@ export class PublicationFormMV { if(!PublicationAttachmentEntity.hasChunkManger) { const fileBlob = PublicationAttachmentEntity.blobFile; - const fileChunks = new Chunks({chunkSize: 2000 }) + const fileChunks = new Chunks({chunkSize: 70 }) fileChunks.setFile(fileBlob) PublicationAttachmentEntity.setChunkManger(fileChunks) - PublicationAttachmentEntity.chucksManager.registerOnLastChunk(()=> { + PublicationAttachmentEntity.chucksManager.registerOnLastChunk(() => { + + console.log("last chunk ===============================================") const guid = PublicationAttachmentEntity.chucksManager.path this.ObjectMergeNotification.subscribe(guid, (data) => { @@ -246,29 +236,36 @@ export class PublicationFormMV { }) }) - } else { - if(PublicationAttachmentEntity.chucksManager.doneUpload) { - alert("done") - return resolve(true) - } + } else if(PublicationAttachmentEntity.chucksManager.doneUpload) { + return resolve(true) } - if( PublicationAttachmentEntity.chucksManager.isUploading == false) { - PublicationAttachmentEntity.chucksManager.setUploading() - const result = await this.UploadFileUseCase.execute(PublicationAttachmentEntity) - PublicationAttachmentEntity.chucksManager.clearUploading() - PublicationAttachmentEntity.chucksManager.setManualRetry() + let attemp = 0; + let result: Result + if( PublicationAttachmentEntity.chucksManager.isUploading == 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') + + PublicationAttachmentEntity.chucksManager.setManualRetry() + PublicationAttachmentEntity.chucksManager.doneChunkUpload() if(result.isErr()) { - alert("error") - - reject(false) + resolve(false) } else { - alert("passs") + resolve(true) } + } else { - alert("not") + } }) @@ -276,36 +273,41 @@ export class PublicationFormMV { } uploadVideosFiles(): Promise { - return new Promise((resolve, reject)=> { - const videosFiles = this.getVideoFiles() - const videosFilesToUploads = videosFiles.filter( e => e.FileType == "video") + return new Promise((resolve, reject) => { - const Promises: Promise[] = [] + // this.ObjectMergeNotification.socket.registerWhenConnected(() => { + const videosFiles = this.getVideoFiles() - for(const file of videosFilesToUploads) { - const promise = this.upload(file) - Promises.push(promise) - } + const videosFilesToUploads = videosFiles.filter( e => e.FileType == "video") - // 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); + const Promises: Promise[] = [] - if (allPromisesResolvedSuccessfully) { - console.log('All promises resolved successfully.'); - resolve(true) - } else { - reject(false) - console.log('Some promises failed to resolve successfully.'); + for(const file of videosFilesToUploads) { + const promise = this.upload(file) + Promises.push(promise) } - }) - .catch((error) => { - reject(false) - console.error('An error occurred while resolving promises:', error); - }); + + // 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 { + resolve(false) + console.log('Some promises failed to resolve successfully.'); + } + }) + .catch((error) => { + resolve(false) + console.error('An error occurred while resolving promises:', error); + }); + //}) + }) } @@ -325,29 +327,22 @@ export class Chunks { return Math.ceil(this.file.size / this.chunkSize); } - // Function to read a chunk of the file - readChunk(start: number, end: number): Promise { - const file = this.file - - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => { - if (reader.result instanceof ArrayBuffer) { - resolve(reader.result); - } else { - reject(new Error("Failed to read chunk")); - } - }; - - reader.readAsArrayBuffer(file.slice(start, end)); - }); - } - setFile(file: File) { this.file = file } - async getChunks(i: number) { + // Function to read a chunk of the file + readChunk(start: number, end: number): any { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = (event: any) => resolve(event.target.result.split(',')[1]); + reader.onerror = (error) => reject(error); + reader.readAsDataURL(this.file.slice(start, end)); + }); + } + + + async getChunks(i: number): Promise { i-- if(i < this.totalChunks) { const start = i * this.chunkSize; @@ -499,3 +494,4 @@ export class ChucksManager { this.contentReady = true } } + 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 0df78345c..34f8082b1 100644 --- a/src/app/shared/publication/view-publications/view-publications.page.html +++ b/src/app/shared/publication/view-publications/view-publications.page.html @@ -39,23 +39,25 @@

{{publicationFolderService.FolderDetails[folderId].Detail}}

- - - -
- + + +
+
+ - + +
+