This commit is contained in:
Peter Maquiran
2024-02-02 10:50:20 +01:00
15 changed files with 449 additions and 380 deletions
+2 -2
View File
@@ -110,8 +110,8 @@ export class TokenInterceptor implements HttpInterceptor {
}),
catchError((error) => {
console.log(error)
SessionStore.user.Authorization = "";
SessionStore.user.RefreshToken = "";
SessionStore.user.Authorization = SessionStore.user.Authorization;
SessionStore.user.RefreshToken = SessionStore.user.RefreshToken;
SessionStore.setInativity(false)
/* SessionStore.setUrlBeforeInactivity(this.router.url); */
+1 -1
View File
@@ -30,7 +30,7 @@ import { StorageService } from 'src/app/services/storage.service';
export class LoginPage implements OnInit {
logstatus: boolean;
username: string = SessionStore.user.Email || environment.defaultuser;
username: string = environment.defaultuser;
password: string = environment.defaultuserpwd;
userattempt: UserForm;
code = []
@@ -265,6 +265,9 @@ export class PublicationsPage implements OnInit {
const loader = this.toastService.loading();
try {
await this.publications.DeletePresidentialAction(id).toPromise();
if(window["refreshPublication"]) {
window["refreshPublication"]();
}
this.toastService._successMessage()
} catch (error) {
if(error.status == 0) {
@@ -270,6 +270,7 @@ export class ViewPublicationsPage implements OnInit {
if (!found) {
this.publicationFolderService.publicationList[folderId].push(publicationDetails)
this.publicationFolderService.revertPublicationOrder(folderId)
} else {
@@ -348,4 +349,25 @@ export class ViewPublicationsPage implements OnInit {
await modal.present();
}
getSortedPublications(): Publication[] {
const unsortedPublications = this.publicationFolderService.publicationList[this.folderId];
if (unsortedPublications) {
// Copiar a lista original para evitar alterações indesejadas
const publicationsCopy = [...unsortedPublications];
// Ordenar as publicações pelo DatePublication
publicationsCopy.sort((a, b) => {
const dateA = new Date(a.DatePublication).getTime();
const dateB = new Date(b.DatePublication).getTime();
return dateA - dateB;
});
return publicationsCopy;
} else {
return [];
}
}
}
+10 -4
View File
@@ -334,22 +334,28 @@ export class RoomService {
message.loadHistory = this.DoneLoadingHistory
this.lastMessage = message;
this.calDateDuration(ChatMessage._updatedAt);
try {
this.calDateDuration(ChatMessage._updatedAt);
} catch (error) {
console.log(error)
}
if (message.t == 'r') {
this.name = message.msg;
}
if (this.isSenderIsNotMe(ChatMessage)) {
//if (this.isSenderIsNotMe(ChatMessage)) {
/* this.NativeNotificationService.sendNotificationChat({
message: message.msg,
title: this.name
}); */
}
//}
if (this.hasLoadHistory == true) {
this.messages.push(message)
await message.addMessageDB()
message.addMessageDB()
} else {
this.messagesBeforeOfflineAPI.push(message)
}
+217 -186
View File
@@ -67,157 +67,75 @@ 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 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());
// })
// .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
// setTimeout(() => {
// this.connect();
// }, 1000); // Adjust the delay as needed
// 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.');
// }
// }
// close() {
// if (this.isOpen) {
// this.socket.close();
// 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);
// });
// }
// }
@@ -237,67 +155,95 @@ interface socketResponse {
// }
// }
// export class ObjectMergeNotification{
interface socketResponse {
// //socket = new ReconnectingWebSocket('ws://localhost:3002');
// callbacks: {[GUID: string]: Function} = {}
// runWatch = true
// CMAPIService: CMAPIService = window["CMAPIAPIRepository"]
index: string
Guid: string
IsCompleted: Boolean
}
class ReconnectingWebSocket {
// constructor() {
// // this.socket.onDisconnectCallback(()=> {
// // this.runWatch = true
// // this.watch()
// // })
private url: string
private socket
isOpen: boolean
private callbacks: Function[] = []
private onDisconnect: Function[] = []
private onConnect: Function[] = []
private stop = true
http: HttpClient = window["http"]
// // this.socket.onConnectCallback(()=> {
// // this.runWatch = false
// // })
constructor(url) {
this.url = url;
this.socket = null;
this.isOpen = false;
this.connect();
}
// // this.socket.subscribe((data: socketResponse) => {
// // if(data.IsCompleted == true) {
// // this.callbacks[data.Guid](data)
// // delete this.callbacks[data.Guid]
// // }
// // })
connect() {
this.socket = new WebSocket(this.url);
// this.watch()
// }
this.socket.addEventListener('open', (event) => {
this.isOpen = true;
console.log('WebSocket connection established');
// async watch() {
// if(this.runWatch) {
// setTimeout(async ()=> {
// for(const [key, funx] of Object.entries(this.callbacks)) {
// Example: Send a message to the server
this.socket.send('Hello, WebSocket Server!');
this.onConnect.forEach(callback => callback());
});
// const request = await this.CMAPIService.getVideoHeader(key)
this.socket.addEventListener('message', (event) => {
const data: socketResponse = JSON.parse(event.data)
this.callbacks.forEach(callback => callback(data));
});
// if(request.isOk()) {
// funx()
// delete this.callbacks[key]
// }
// }
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
}
});
}
// this.watch()
// }, 1000)
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);
}
// subscribe(GUID, callback:Function) {
// this.callbacks[GUID] = callback;
// }
// unsubscribe(GUID) {
// delete this.callbacks[GUID]
// }
// }
unsubscribe(callback) {
this.callbacks = this.callbacks.filter(cb => cb !== callback);
}
onDisconnectCallback(callback) {
this.onDisconnect.push(callback)
}
onConnectCallback(callback) {
this.onConnect.push(callback)
}
}
export class ObjectMergeNotification{
socket = new ReconnectingWebSocketSignalR()
socket = new ReconnectingWebSocket('ws://localhost:3002');
callbacks: {[GUID: string]: Function} = {}
runWatch = true
CMAPIService: CMAPIService = window["CMAPIAPIRepository"]
@@ -311,32 +257,25 @@ export class ObjectMergeNotification{
})
this.socket.onConnectCallback(()=> {
console.log("open trigger")
this.runWatch = false
})
this.socket.subscribe((data: socketResponse) => {
if(data.IsCompleted == true) {
console.log("==================!!!====================")
this.callbacks[data.Guid](data)
delete this.callbacks[data.Guid]
try {
this.callbacks[data.Guid](data)
delete this.callbacks[data.Guid]
} catch (error) {}
} else {
console.log("else", data)
}
})
this.socket.connect();
this.watch()
}
close() {
this.socket.disconnect();
this.watchCount = 0;
this.runWatch = false
}
async watch() {
this.watchCount = 0;
@@ -368,6 +307,12 @@ export class ObjectMergeNotification{
}
}
close() {
this.socket.disconnect();
this.watchCount = 0;
this.runWatch = false
}
subscribe(GUID, callback:Function) {
this.callbacks[GUID] = callback;
}
@@ -377,3 +322,89 @@ 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()
// }
// 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]
// }
// }
@@ -186,9 +186,9 @@ export class MiddlewareServiceService {
const headers = new HttpHeaders();
headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization);
// const geturl = 'http://localhost:3001/FileHub';
const geturl = 'http://localhost:3001/FileHub';
// const geturl = environment.apiURL + 'Tasks/DelegateTask';
const geturl = environment.apiPCURL + 'FileContent';
// const geturl = environment.apiPCURL + 'FileContent';
let options = {
headers: headers
@@ -71,11 +71,6 @@
<source type="video/mp4" [src]="seleted.url">
</video>
<video *ngIf="checkFileType.checkFileType(seleted.FileExtension) == 'video' && checkTableDivice() == true" width="70" height="70"
preload="metadata" webkit-playsinline="webkit-playsinline">
<source type="video/mp4" [src]="'data:video/mp4;base64,' +seleted.Base64">
</video>
<ion-icon *ngIf="seleted?.chucksManager?.manualRetry" src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon>
</div>
@@ -253,26 +253,26 @@ export class NewPublicationPage implements OnInit {
multiple: true,
});
console.log(result)
console.log(result)
result.files.forEach(async blobFile => {
console.log(blobFile)
if (this.checkFileType.checkFileType(blobFile.mimeType) == 'image' || this.checkFileType.checkFileType(blobFile.mimeType) == 'video') {
/* console.log('converte new way',this.getBase64(blobFile)) */
/* console.log('converte new way',this.getBase64(blobFile)) */
/* const blob = await fetch(
Capacitor.convertFileSrc(blobFile.path)
).then(r => r.blob()); */
/* const blob = await fetch(
Capacitor.convertFileSrc(blobFile.path)
).then(r => r.blob()); */
/* console.log(await blob.arrayBuffer());
console.log("base64 :data:video/mp4;base64,",this.arrayBufferToBase64(await blob.arrayBuffer())) */
/* console.log(await blob.arrayBuffer());
console.log("base64 :data:video/mp4;base64,",this.arrayBufferToBase64(await blob.arrayBuffer())) */
this.convertBlobToBase64(blobFile.blob).then((value: string) => {
console.log(value)
console.log(this.removeTextBeforeSlash(value, ','))
this.filesSizeSum = this.filesSizeSum + blobFile.size
if (this.fileSizeToMB(this.filesSizeSum) <= 20) {
@@ -283,7 +283,7 @@ export class NewPublicationPage implements OnInit {
const newAttachment = new PublicationAttachmentEntity(
{
base64: value,
base64: this.removeTextBeforeSlash(value, ','),
extension: FileExtension,
blobFile: file,
FileType: this.checkFileType.checkFileType(FileExtension) as any,
@@ -343,7 +343,7 @@ export class NewPublicationPage implements OnInit {
({
multiple: true,
});
console.log(result.files)
console.log(result.files)
result.files.forEach(element => {
this.filesSizeSum = this.filesSizeSum + element.size
@@ -355,15 +355,16 @@ export class NewPublicationPage implements OnInit {
.then(async (content) => {
console.log(result)
console.log('load video tablet base64',content)
console.log('load video tablet base64', content)
this.filecontent = true;
let fileObject = new PublicationAttachmentEntity ({
let fileObject = new PublicationAttachmentEntity({
base64: content.data,
extension: this.removeTextBeforeSlash(element.mimeType, '/'),
OriginalFileName: 'video',
FileType: this.checkFileType.checkFileType( this.removeTextBeforeSlash(element.mimeType, '/')) as any
})
this.seletedContent.push(fileObject)
console.log('Files array',this.seletedContent)
})
.catch((err) => console.error(err));
} catch (error) {
@@ -638,17 +639,59 @@ export class NewPublicationPage implements OnInit {
}
convertBlobToBase64(blob: Blob) {
console.log('Convert blob ',blob)
return new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result)
}
reader.readAsDataURL(blob)
},)
try {
return new Promise((resolve, reject) => {
const chunkSize = 5000000; // 5 MB
const fileSize = blob.size;
const chunks = Math.ceil(fileSize / chunkSize);
let currentChunk = 0;
const base64Chunks = [];
const reader = new FileReader();
reader.onload = function () {
base64Chunks.push(reader.result);
currentChunk++;
if (currentChunk < chunks) {
loadNextChunk();
} else {
const base64Data = base64Chunks.join("");
resolve(base64Data);
}
};
reader.onerror = function (error) {
reject(error);
};
function loadNextChunk() {
const start = currentChunk * chunkSize;
const end = Math.min(start + chunkSize, fileSize);
const chunk = blob.slice(start, end);
reader.readAsDataURL(chunk);
}
loadNextChunk();
});
} catch (error) {
console.log(error);
}
}
/* convertBlobToBase64(blob: Blob) {
console.log('Convert blob ',blob)
return new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result)
}
reader.readAsDataURL(blob)
},)
} */
getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -656,7 +699,7 @@ export class NewPublicationPage implements OnInit {
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
}
removeTextBeforeSlash(inputString, mark) {
if (inputString.includes(mark)) {
@@ -1031,7 +1074,7 @@ export class NewPublicationPage implements OnInit {
.then(async (content) => {
this.filecontent = true;
console.log('',content)
console.log('', content)
let fileObject = new PublicationAttachmentEntity({
base64: content.data,
extension: 'mp4',
@@ -1057,7 +1100,7 @@ export class NewPublicationPage implements OnInit {
}
checkTableDivice() {
if (!this.platform.is('desktop'))
if (this.platform.is('tablet'))
return true;
}
@@ -41,7 +41,10 @@ class UploadFileUseCase {
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))
}
@@ -60,7 +63,6 @@ class UploadFileUseCase {
const pingRequest = await this.CMAPIService.ping()
if( pingRequest.isErr()) {
connection = false
PublicationAttachmentEntity.chucksManager.setManualRetry()
return reject(err(PublicationAttachmentEntity))
}
} else {
@@ -85,24 +87,31 @@ class UploadFileUseCase {
}
if(!connection) {
PublicationAttachmentEntity.chucksManager.clearUploading()
PublicationAttachmentEntity.chucksManager.setManualRetry()
return reject(err(PublicationAttachmentEntity))
} else {
} 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.setManualRetry()
return reject(err(PublicationAttachmentEntity))
}
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))
}
} else {
PublicationAttachmentEntity.chucksManager.doneChunkUpload()
resolve(ok(PublicationAttachmentEntity))
return resolve(ok(PublicationAttachmentEntity))
}
@@ -222,7 +231,7 @@ export class PublicationFormMV {
if(!PublicationAttachmentEntity.hasChunkManger) {
const fileBlob = PublicationAttachmentEntity.blobFile;
const fileChunks = new Chunks({chunkSize: 500 })
const fileChunks = new Chunks({chunkSize: 2000 })
fileChunks.setFile(fileBlob)
PublicationAttachmentEntity.setChunkManger(fileChunks)
@@ -239,6 +248,7 @@ export class PublicationFormMV {
} else {
if(PublicationAttachmentEntity.chucksManager.doneUpload) {
alert("done")
return resolve(true)
}
}
@@ -247,10 +257,18 @@ export class PublicationFormMV {
PublicationAttachmentEntity.chucksManager.setUploading()
const result = await this.UploadFileUseCase.execute(PublicationAttachmentEntity)
PublicationAttachmentEntity.chucksManager.clearUploading()
PublicationAttachmentEntity.chucksManager.setManualRetry()
if(result.isErr()) {
alert("error")
reject(false)
} else {
alert("passs")
}
} else {
alert("not")
}
})
@@ -225,6 +225,7 @@ export class ViewPublicationsPage implements OnInit {
if (!found) {
this.publicationFolderService.publicationList[folderId].push(publicationDetails)
this.publicationFolderService.revertPublicationOrder(folderId)
} else {
let a: any = Object.assign({},this.publicationFolderService.publicationList[folderId][findIndex])
+47 -30
View File
@@ -10,8 +10,8 @@ import { PublicationPipe } from 'src/app/pipes/publication.pipe';
})
export class PublicationFolderService {
publicationList: {[key: string]: Publication[] } = {};
FolderDetails: {[key: string]: PublicationFolder } = {};
publicationList: { [key: string]: Publication[] } = {};
FolderDetails: { [key: string]: PublicationFolder } = {};
restoreFolder: {} = {}
@@ -25,14 +25,14 @@ export class PublicationFolderService {
constructor(
private storage: Storage,
private publications: PublicationsService,
) {}
) { }
createPublicationList(folderId) {
if(!this.publicationList[folderId]) {
if (!this.publicationList[folderId]) {
this.publicationList[folderId] = []
}
if(!this.FolderDetails[folderId]) {
if (!this.FolderDetails[folderId]) {
this.FolderDetails[folderId] = new PublicationFolder();
}
}
@@ -40,13 +40,13 @@ export class PublicationFolderService {
getFromDB(folderId: any) {
if(!this.restoreFolder[folderId]) {
if (!this.restoreFolder[folderId]) {
this.storage.get(folderId).then((viewPublications) => {
this.publicationList[folderId] = viewPublications
})
this.storage.get(folderId+"name").then((viewPublications) => {
this.storage.get(folderId + "name").then((viewPublications) => {
this.FolderDetails[folderId] = viewPublications
})
}
@@ -56,29 +56,30 @@ export class PublicationFolderService {
updateFolderDetails(folderId, res) {
this.FolderDetails[folderId] = res
this.storage.set(folderId+"name", res)
this.storage.set(folderId + "name", res)
}
save(folderId) {
this.storage.set(folderId+"name", this.FolderDetails)
this.storage.set(folderId + "name", this.FolderDetails)
this.storage.set(folderId, this.publicationList[folderId]);
}
publicationIsPresent(publicationId, folderId) {
return this.publicationList[folderId].find( e => e.DocumentId == publicationId )
return this.publicationList[folderId].find(e => e.DocumentId == publicationId)
}
publicationFind(publicationId, folderId) {
return this.publicationList[folderId].find( e => e.DocumentId == publicationId )
return this.publicationList[folderId].find(e => e.DocumentId == publicationId)
}
publicationFindIndex(publicationId, folderId) {
return this.publicationList[folderId].findIndex( e => e.DocumentId == publicationId )
return this.publicationList[folderId].findIndex(e => e.DocumentId == publicationId)
}
PublicationAddOrUpdate(folderId, publicationId, Publication: Publication) {
const findIndex = this.publicationFindIndex(publicationId, folderId)
const found = this.publicationIsPresent(publicationId, folderId)
if(!found) {
if (!found) {
this.publicationList[folderId].push(Publication)
this.revertPublicationOrder(folderId);
} else {
this.publicationList[folderId][findIndex] = Publication
}
@@ -86,9 +87,9 @@ export class PublicationFolderService {
deletePost(folderId: any, DocumentId: any) {
if(this.publicationList[folderId]) {
if (this.publicationList[folderId]) {
this.publicationList[folderId] = this.publicationList[folderId].filter( e => e.DocumentId != DocumentId)
this.publicationList[folderId] = this.publicationList[folderId].filter(e => e.DocumentId != DocumentId)
this.save(folderId)
}
@@ -99,7 +100,7 @@ export class PublicationFolderService {
this.publications.GetPresidentialAction(folderId).subscribe(res => {
this.FolderDetails[folderId] = res
this.storage.set(folderId+"name", res)
this.storage.set(folderId + "name", res)
}, (error) => {
this.showLoader = false;
// this.httpErroHandle.httpStatusHandle(error)
@@ -118,7 +119,7 @@ export class PublicationFolderService {
let loadLater = []
for (let publicationId of publicationIds) {
if(!this.publicationIsPresent(publicationId, folderId)) {
if (!this.publicationIsPresent(publicationId, folderId)) {
await this.loadPublication(publicationId, folderId)
} else {
@@ -126,7 +127,7 @@ export class PublicationFolderService {
}
}
for( let publicationId of loadLater) {
for (let publicationId of loadLater) {
await this.loadPublication(publicationId, folderId)
}
@@ -134,7 +135,7 @@ export class PublicationFolderService {
this.storage.set(folderId, this.publicationList[folderId]);
this.getpublication = this.publicationList[folderId];
} catch(error) {
} catch (error) {
this.showLoader = false;
}
@@ -147,17 +148,18 @@ export class PublicationFolderService {
const findIndex = this.publicationFindIndex(publicationId, folderId)
const found = this.publicationIsPresent(publicationId, folderId)
if(!found) {
if (!found) {
this.publicationList[folderId].push(publicationDetails)
this.revertPublicationOrder(folderId);
} else {
let a: any = Object.assign({},this.publicationList[folderId][findIndex])
let a: any = Object.assign({}, this.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)) {
if (JSON.stringify(a) != JSON.stringify(b)) {
// console.log({a, b})
this.publicationList[folderId][findIndex] = publicationDetails
@@ -171,9 +173,10 @@ export class PublicationFolderService {
async CreatePublication(folderId, publication: Publication) {
const response = await this.publications.CreatePublication(folderId, publication).toPromise()
const response = await this.publications.CreatePublication(folderId, publication).toPromise()
let publicationDetails: Publication = this.publicationPipe.itemList(response)
this.publicationList[folderId].push(publicationDetails)
this.revertPublicationOrder(folderId)
return publicationDetails
}
@@ -182,8 +185,9 @@ export class PublicationFolderService {
const findIndex = this.publicationFindIndex(publicationId, folderId)
const found = this.publicationIsPresent(publicationId, folderId)
if(!found) {
if (!found) {
this.publicationList[folderId].push(publicationDetails)
this.revertPublicationOrder(folderId)
} else {
this.publicationList[folderId][findIndex] = publicationDetails
}
@@ -196,8 +200,10 @@ export class PublicationFolderService {
const findIndex = this.publicationFindIndex(publicationId, folderId)
const found = this.publicationIsPresent(publicationId, folderId)
if(!found) {
if (!found) {
this.publicationList[folderId].push(publicationDetails)
this.revertPublicationOrder(folderId);
} else {
return this.publicationList[folderId][findIndex]
}
@@ -205,10 +211,10 @@ export class PublicationFolderService {
}
getLocalPublication (folderId, DocumentId) {
getLocalPublication(folderId, DocumentId) {
if(this.publicationList[folderId]) {
return this.publicationList[folderId].find( e => e.DocumentId == DocumentId )
if (this.publicationList[folderId]) {
return this.publicationList[folderId].find(e => e.DocumentId == DocumentId)
} else {
}
@@ -217,11 +223,22 @@ export class PublicationFolderService {
PublicationHasImage(Publication: Publication) {
return Publication?.Files?.[0]?.FileBase64 != '' && Publication?.Files?.[0]?.FileBase64 != "data:image/jpg;base64,null"
return Publication?.Files?.[0]?.FileBase64 != '' && Publication?.Files?.[0]?.FileBase64 != "data:image/jpg;base64,null"
}
hasCapturedImage(Publication: Publication) {
return Publication?.Files?.[0]?.FileBase64 != '' && Publication?.Files?.[0]?.FileBase64 != "data:image/jpg;base64,null"
return Publication?.Files?.[0]?.FileBase64 != '' && Publication?.Files?.[0]?.FileBase64 != "data:image/jpg;base64,null"
}
revertPublicationOrder(folderId) {
//Revert order of the list
if (this.publicationList[folderId]) {
this.publicationList[folderId] = this.publicationList[folderId].sort((a, b) => {
const dateA = new Date(a.DatePublication).getTime();
const dateB = new Date(b.DatePublication).getTime();
return dateB - dateA; // Revertendo a ordem aqui
})
}
}
}