-
+
@@ -101,7 +101,7 @@

{{ allProcessesList.length }} Documentos

-
+
@@ -128,24 +128,24 @@
-

Pendentes

-

Meus Pendentes

+

Pendentes

+

Meus Pendentes

{{pendentesstore.count}} Documentos

-
+
-

Despacho do Presidente da República

-

Despachos criados por mim

+

Despacho do Presidente da República

+

Despachos criados por mim

{{ despachoprstore.count }} Documentos

-
+
@@ -163,8 +163,8 @@
-

Pedidos de Parecer

-

Pedidos de Parecer solicitados por mim

+

Pedidos de Parecer

+

Pedidos de Parecer solicitados por mim

{{pedidosstore.countparecer}} Documentos

@@ -193,7 +193,7 @@
--> -
+
@@ -208,31 +208,31 @@
-
+
-

Diplomas por Validar

-

Diplomas por Assinar

+

Diplomas por Validar

+

Diplomas por Assinar

{{ deplomasStore.deplomasReviewCount }} Documentos

-
+
-

Diplomas assinados PR

-

Diplomas

+

Diplomas assinados PR

+

Diplomas

{{ deplomasStore.countDiplomasAssinadoListCount }} Documentos

-
+
diff --git a/src/app/pages/gabinete-digital/gabinete-digital.page.ts b/src/app/pages/gabinete-digital/gabinete-digital.page.ts index 285af08d2..5634ab2ec 100644 --- a/src/app/pages/gabinete-digital/gabinete-digital.page.ts +++ b/src/app/pages/gabinete-digital/gabinete-digital.page.ts @@ -22,7 +22,7 @@ import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe'; //import { NotificationsService } from 'src/app/services/notifications.service'; import { DespachoService } from 'src/app/Rules/despacho.service'; import { ChangeProfileService } from 'src/app/services/change-profile.service'; -import { PermissionService } from 'src/app/services/worker/permission.service'; +import { PermissionService } from 'src/app/services/permission.service'; import { ThemeService } from 'src/app/services/theme.service' @@ -115,6 +115,9 @@ export class GabineteDigitalPage implements OnInit, DoCheck { customTaskPipe = new CustomTaskPipe() + permissions = { + Agenda: 530 + } @ViewChild(ExpedientsPage) expedientesPage: ExpedientsPage; @ViewChild(PendentesPage) pendentesListPage: PendentesPage; @ViewChild(EventsToApprovePage) eventsToApprove: EventsToApprovePage; @@ -125,7 +128,6 @@ export class GabineteDigitalPage implements OnInit, DoCheck { private activatedRoute: ActivatedRoute, private router: Router, authService: AuthService, - public p: PermissionService, public waitForDomService: WaitForDomService, //private notificationsService: NotificationsService, private despachoRule: DespachoService, @@ -136,7 +138,8 @@ export class GabineteDigitalPage implements OnInit, DoCheck { public ThemeService: ThemeService, private sortService: SortService, private dataService: DataService, - private storage: Storage + private storage: Storage, + public p: PermissionService, ) { this.loggeduser = authService.ValidatedUser; @@ -256,7 +259,7 @@ export class GabineteDigitalPage implements OnInit, DoCheck { let date = new Date(element.taskStartDate); date.setMonth(date.getMonth() + 1); let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); - + let task = { "SerialNumber": element.serialNumber, "Folio": element.workflowInstanceDataFields.Subject, @@ -274,11 +277,11 @@ export class GabineteDigitalPage implements OnInit, DoCheck { "Agenda": element.workflowInstanceDataFields.Agenda, "customDate": this.setFormatDate(new Date(element.workflowInstanceDataFields.StartDate), new Date(element.workflowInstanceDataFields.EndDate), element.workflowInstanceDataFields.IsAllDayEvent), } - + this.allProcessesList.push(task); this.allProcessesList = removeDuplicate(this.allProcessesList); this.allProcessesList = this.sortService.sortDate(this.allProcessesList, 'CreateDate') - + }); }) } else { @@ -287,9 +290,9 @@ export class GabineteDigitalPage implements OnInit, DoCheck { let date = new Date(element.taskStartDate); date.setMonth(date.getMonth() + 1); let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); - + var workflowInstanceDataFields = JSON.parse(element.workflowInstanceDataFields); - + let task = { "SerialNumber": element.serialNumber, "Folio": workflowInstanceDataFields.Subject, @@ -306,11 +309,11 @@ export class GabineteDigitalPage implements OnInit, DoCheck { "Agenda": workflowInstanceDataFields.Agenda, "customDate": this.setFormatDate(new Date(workflowInstanceDataFields.StartDate), new Date(workflowInstanceDataFields.EndDate), workflowInstanceDataFields.IsAllDayEvent), } - + this.allProcessesList.push(task); this.allProcessesList = removeDuplicate(this.allProcessesList) this.allProcessesList = this.sortService.sortDate(this.allProcessesList, 'CreateDate') - + }); console.log("All process from db ", allprocess) }) diff --git a/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.html b/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.html index 9801094f5..4f33afd8d 100644 --- a/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.html +++ b/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.html @@ -89,7 +89,7 @@ - +
@@ -99,7 +99,7 @@ - +
@@ -110,14 +110,14 @@ - +
- +
@@ -127,7 +127,7 @@ - +
diff --git a/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.ts b/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.ts index 0874bd07e..79204effd 100644 --- a/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.ts +++ b/src/app/pages/gabinete-digital/pedidos/pedido/pedido.page.ts @@ -23,7 +23,7 @@ import { PedidoService } from 'src/app/Rules/pedido.service'; import { SqliteService } from 'src/app/services/sqlite.service'; import { BackgroundService } from 'src/app/services/background.service'; -import { PermissionService } from 'src/app/services/worker/permission.service'; +import { PermissionService } from 'src/app/services/permission.service'; import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page'; import { ThemeService } from 'src/app/services/theme.service' import { DataService } from 'src/app/services/data.service'; diff --git a/src/app/pages/login/login.page.ts b/src/app/pages/login/login.page.ts index 37a27b44f..a915cdc21 100644 --- a/src/app/pages/login/login.page.ts +++ b/src/app/pages/login/login.page.ts @@ -12,6 +12,8 @@ import { ChangeProfileService } from 'src/app/services/change-profile.service'; import { ThemeService } from 'src/app/services/theme.service'; import { StorageService } from 'src/app/services/storage.service'; import { ChatService } from 'src/app/services/chat.service'; +import { PermissionService } from 'src/app/services/permission.service'; +import { PermissionList } from 'src/app/models/permission/permissionList'; @Component({ selector: 'app-login', @@ -29,7 +31,8 @@ export class LoginPage implements OnInit { hasPin: boolean loginPreference: string - sessionStore = SessionStore + sessionStore = SessionStore; + permissionList = new PermissionList(); constructor( private notificatinsservice: NotificationsService, @@ -40,7 +43,8 @@ export class LoginPage implements OnInit { private clearStoreService: ClearStoreService, private changeProfileService: ChangeProfileService, public ThemeService: ThemeService, - private storageservice: StorageService + private storageservice: StorageService, + public permissionService: PermissionService, ) {} ngOnInit() { @@ -101,26 +105,29 @@ export class LoginPage implements OnInit { // login to API successfully if (attempt) { if (attempt.UserId == SessionStore.user.UserId) { + await this.authService.SetSession(attempt, this.userattempt); await this.authService.loginChat(); - await this.authService.loginToChatWs() + await this.authService.loginToChatWs(); this.getToken(); SessionStore.setInativity(true); - this.goback() + this.goback(); + } else { - this.clearStoreService.clear() - SessionStore.delete() + this.clearStoreService.clear(); + SessionStore.delete(); window.localStorage.clear(); await this.authService.SetSession(attempt, this.userattempt); - this.changeProfileService.run() + this.changeProfileService.run(); await this.authService.loginChat(); - await this.authService.loginToChatWs() + await this.authService.loginToChatWs(); this.getToken(); this.router.navigateByUrl('/pin', { replaceUrl: true }); + } } else{ @@ -141,7 +148,16 @@ export class LoginPage implements OnInit { if(pathName) { this.router.navigate([pathName]); } else { - this.router.navigate(['/home/events']); + if(this.permissionService.userPermission(this.permissionList.Agenda.access) || this.permissionService.userPermission(this.permissionList.Gabinete.access)){ + this.router.navigate(['/home/events']); + } + else if(this.permissionService.userPermission(this.permissionList.Chat.access) && this.permissionService.userPermission(this.permissionList.Actions.access)){ + this.router.navigate(['/home/chat']); + } + else if(this.permissionService.userPermission(this.permissionList.Actions.access)){ + alert('here') + this.router.navigate(['/home/publications']); + } } } diff --git a/src/app/pages/publications/publication-detail/publication-detail.page.html b/src/app/pages/publications/publication-detail/publication-detail.page.html index ea16990a6..d778e071d 100644 --- a/src/app/pages/publications/publication-detail/publication-detail.page.html +++ b/src/app/pages/publications/publication-detail/publication-detail.page.html @@ -56,12 +56,12 @@ - + - + diff --git a/src/app/pages/publications/publication-detail/publication-detail.page.ts b/src/app/pages/publications/publication-detail/publication-detail.page.ts index 17681b2cc..84b8746e0 100644 --- a/src/app/pages/publications/publication-detail/publication-detail.page.ts +++ b/src/app/pages/publications/publication-detail/publication-detail.page.ts @@ -10,6 +10,7 @@ import { SqliteService } from 'src/app/services/sqlite.service'; import { BackgroundService } from 'src/app/services/background.service'; import { ThemeService } from 'src/app/services/theme.service' import { RouteService } from 'src/app/services/route.service'; +import { PermissionService } from 'src/app/services/permission.service'; @Component({ selector: 'app-publication-detail', @@ -31,7 +32,8 @@ export class PublicationDetailPage implements OnInit { private RouteService: RouteService, private sqliteservice: SqliteService, private backgroundservice: BackgroundService, - public ThemeService: ThemeService ) { + public ThemeService: ThemeService, + public p:PermissionService ) { this.publicationId = this.navParams.get('publicationId'); /* this.folderId = this.navParams.get('folderIdId'); */ diff --git a/src/app/pages/publications/publications.page.html b/src/app/pages/publications/publications.page.html index 3abc2e9ec..622dd150e 100644 --- a/src/app/pages/publications/publications.page.html +++ b/src/app/pages/publications/publications.page.html @@ -25,7 +25,7 @@ Acções Presidenciais
- @@ -92,14 +92,14 @@
- + - + diff --git a/src/app/pages/publications/publications.page.ts b/src/app/pages/publications/publications.page.ts index 77f1df29a..4baeee66c 100644 --- a/src/app/pages/publications/publications.page.ts +++ b/src/app/pages/publications/publications.page.ts @@ -15,6 +15,7 @@ import { SqliteService } from 'src/app/services/sqlite.service'; import { BackgroundService } from 'src/app/services/background.service'; import { ThemeService } from 'src/app/services/theme.service' import { Storage } from '@ionic/storage'; +import { PermissionService } from 'src/app/services/permission.service'; @Component({ @@ -68,7 +69,8 @@ export class PublicationsPage implements OnInit { private backgroundservice: BackgroundService, private platform: Platform, public ThemeService: ThemeService, - private storage: Storage + private storage: Storage, + public p: PermissionService, ) { this.months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]; diff --git a/src/app/pages/publications/view-publications/publication-detail/publication-detail.page.html b/src/app/pages/publications/view-publications/publication-detail/publication-detail.page.html index dd6e0bbb6..7b06bd70d 100644 --- a/src/app/pages/publications/view-publications/publication-detail/publication-detail.page.html +++ b/src/app/pages/publications/view-publications/publication-detail/publication-detail.page.html @@ -61,12 +61,12 @@ - + - + diff --git a/src/app/pages/publications/view-publications/publication-detail/publication-detail.page.ts b/src/app/pages/publications/view-publications/publication-detail/publication-detail.page.ts index 15afbe6e2..9929de9ef 100644 --- a/src/app/pages/publications/view-publications/publication-detail/publication-detail.page.ts +++ b/src/app/pages/publications/view-publications/publication-detail/publication-detail.page.ts @@ -10,6 +10,7 @@ import { Location } from '@angular/common'; import { ThemeService } from 'src/app/services/theme.service' import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { RouteService } from 'src/app/services/route.service'; +import { PermissionService } from 'src/app/services/permission.service'; @Component({ selector: 'app-publication-detail', @@ -31,7 +32,8 @@ export class PublicationDetailPage implements OnInit { private activatedRoute: ActivatedRoute, private router: Router, private RouteService: RouteService, - public ThemeService: ThemeService + public ThemeService: ThemeService, + public p:PermissionService, ) { this.activatedRoute.paramMap.subscribe(params => { diff --git a/src/app/pages/publications/view-publications/view-publications.page.html b/src/app/pages/publications/view-publications/view-publications.page.html index 847b460c5..8ed7372e8 100644 --- a/src/app/pages/publications/view-publications/view-publications.page.html +++ b/src/app/pages/publications/view-publications/view-publications.page.html @@ -15,7 +15,7 @@

{{item.Detail}}

-
+
@@ -33,7 +33,9 @@ -->
- +
@@ -57,10 +59,10 @@ *ngFor="let publication of getpublication" (click)="goToPublicationDetail(publication.DocumentId)" > - +
- +
diff --git a/src/app/pages/publications/view-publications/view-publications.page.ts b/src/app/pages/publications/view-publications/view-publications.page.ts index b8c63dfb3..5a7bb8264 100644 --- a/src/app/pages/publications/view-publications/view-publications.page.ts +++ b/src/app/pages/publications/view-publications/view-publications.page.ts @@ -12,6 +12,7 @@ import { BackgroundService } from 'src/app/services/background.service'; import { ThemeService } from 'src/app/services/theme.service' import { forkJoin } from 'rxjs'; import { ToastService } from 'src/app/services/toast.service'; +import { PermissionService } from 'src/app/services/permission.service'; @Component({ selector: 'app-view-publications', @@ -42,7 +43,8 @@ export class ViewPublicationsPage implements OnInit { private sqliteservice: SqliteService, private backgroundservice: BackgroundService, public ThemeService: ThemeService, - private toastService: ToastService,) { + private toastService: ToastService, + public p: PermissionService,) { this.item = new PublicationFolder(); this.activatedRoute.paramMap.subscribe(params => { @@ -259,7 +261,7 @@ export class ViewPublicationsPage implements OnInit { publicationArray.push(publicationlis); }); - + this.publicationList = publicationArray; }) } diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 510b05fa1..f4f015d41 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -18,6 +18,7 @@ import { ProcessesService } from 'src/app/services/processes.service'; import { AttachmentsService } from 'src/app/services/attachments.service'; import { RoomService } from './chat/room.service'; import { Storage } from '@ionic/storage'; +import { InitialsService } from './functions/initials.service'; @Injectable({ providedIn: 'root' @@ -44,7 +45,8 @@ export class AuthService { private NfService:NfService, private processesService: ProcessesService, private AttachmentsService: AttachmentsService, - private storage: Storage ) { + private storage: Storage, + private initialsService: InitialsService ) { this.headers = new HttpHeaders(); @@ -74,6 +76,8 @@ export class AuthService { try { response = await this.http.post(environment.apiURL + "UserAuthentication/Login", '', this.opts).toPromise(); + console.log(response); + if(saveSession) { this.SetSession(response, user) } @@ -94,6 +98,9 @@ export class AuthService { } else if(session.RoleID == 100000011) { session.Profile = 'MDGPR' } + else{ + session.Profile = this.initialsService.getInitials(session.FullName); + } session.Password = user.password session.RochetChatUser = user.username.split('@')[0] @@ -124,7 +131,6 @@ export class AuthService { let responseChat = await this.httpService.post('login', postData).toPromise(); if(responseChat) { - console.log('Login to Rocket chat OK', responseChat); this.ValidatedUserChat = responseChat; localStorage.setItem('userChat', JSON.stringify(responseChat)); @@ -169,11 +175,15 @@ export class AuthService { try { let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() message.file.guid = guid.path + + console.log('========================================',guid) // await this.storage.set(guid.path, message.file.image_url).then(() => { // console.log('add picture to chat IMAGE SAVED') // // message.getFileFromDb() // }); + message.downloadFileMsg() + return true } catch(e) { console.log('failed to upload to server', e) diff --git a/src/app/services/chat/chat-methods.service.ts b/src/app/services/chat/chat-methods.service.ts index 61e446163..379d048b5 100644 --- a/src/app/services/chat/chat-methods.service.ts +++ b/src/app/services/chat/chat-methods.service.ts @@ -47,13 +47,8 @@ export class ChatMethodsService { return this.chatService.sendMessage(body) } - deleteMessage(body) { return this.chatService.deleteMessage(body) } - - - - } \ No newline at end of file diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index 472164861..94439411b 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -10,6 +10,9 @@ import { ChatStorageService } from './chat-storage.service' import { ChatMethodsService } from './chat-methods.service' import { MessageModel, DeleteMessageModel } from '../../models/beast-orm' import { AESEncrypt } from '../aesencrypt.service' +import { HttpClient, HttpEventType } from '@angular/common/http'; +import { AttachmentsService } from 'src/app/services/attachments.service'; +import { NetworkServiceService , ConnectionStatus} from 'src/app/services/network-service.service'; @Injectable({ providedIn: 'root' @@ -22,10 +25,10 @@ export class MessageService { msg = '' rid = '' ts = {} - - u = { - name: '', - username: '', + + u = { + name: '', + username: '', _id: "" } @@ -59,7 +62,9 @@ export class MessageService { private WsChatService: WsChatService, private ChatStorageService: ChatStorageService, private ChatMethodsService: ChatMethodsService, - private AESEncrypt: AESEncrypt) { + private AESEncrypt: AESEncrypt, + private AttachmentsService: AttachmentsService, + private NetworkServiceService: NetworkServiceService) { } setData({customFields = {}, channels, mentions, msg ,rid ,ts, u, t, _id, id, _updatedAt, file, attachments, temporaryData, localReference , viewed = [], received = [], delate = false, delateRequest =false, }:Message) { @@ -74,17 +79,21 @@ export class MessageService { this._id = _id this._updatedAt = _updatedAt || new Date().getTime() this.file = file - this.attachments = attachments this.temporaryData = temporaryData this.localReference = localReference || null this.id = id this.delate = delate this.delateRequest = delateRequest + if(this.attachments?.length >= 1 && attachments?.length >= 1) { + this.attachments[0] = Object.assign(this.attachments[0], attachments[0]) + } else { + this.attachments = attachments + } + this.viewed = [...new Set([...viewed,...this.viewed])]; this.received = [...new Set([...received,...this.received])]; - if(!this.ts) { this.offline = true this.messageSend = false @@ -102,7 +111,6 @@ export class MessageService { } if(this.hasFile) { - // this.getFileFromDb() if(this.file.type != 'application/webtrix') { this.displayType = this.file.type.replace('application/','').toUpperCase() } @@ -118,19 +126,6 @@ export class MessageService { return firstName + ' ' + lastName } - // getFileFromDb() { - - // if(this.hasFile) { - // if (this.file.guid) { - // this.storage.get(this.file.guid).then((image) => { - // if(image != null) { - // this.file.image_url = image - // } - // }); - // } - // } - // } - async send(): Promise { this.sendAttempt++; @@ -138,7 +133,7 @@ export class MessageService { if(!this.hasFile) { const params = {roomId:this.rid, msg:this.msg, localReference: this.localReference} - + await this.sendRequest(params) } else { @@ -152,7 +147,7 @@ export class MessageService { this.uploadingFile = false - if(uploadSuccessfully || this.hasSendAttachment == false) { + if(uploadSuccessfully) { this.hasSendAttachment = true this.errorUploadingAttachment = false this.temporaryData = {} @@ -178,7 +173,7 @@ export class MessageService { return new Promise((resolve, reject)=>{ reject(false) }) - + } } @@ -186,34 +181,40 @@ export class MessageService { } async sendRequest(params) { - this.ChatMethodsService.send(params).subscribe( - (response: any) => { - const ChatMessage = response.message - this.messageSend = true - this.redefinedMessage(ChatMessage) - }, - (error) => { - this.WsChatService.registerCallback({ - type: 'reConnect', - funx: async ()=> { - - this.WsChatService.send(params).then(({message, requestId}) => { - let ChatMessage = message.result - this.messageSend = true - this.redefinedMessage(ChatMessage) - - }) - return true - } - }) - } - ) + if(params?.attachments?.image_url) { + delete params?.attachments?.image_url + } + + + + if(this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) { + + this.WsChatService.send(params).then( + (ChatMessage: any) => { + ChatMessage = ChatMessage.message.result + + this.messageSend = true + this.redefinedMessage(ChatMessage) + } + ) + + } else { + this.WsChatService.registerCallback({ + type: 'reConnect', + funx: async ()=> { + + this.send() + return true + } + }) + } + } async redefinedMessage(ChatMessage , update = true) { ChatMessage = this.NfService.fix_updatedAt(ChatMessage) - + const message = this.getChatObj() ChatMessage = Object.assign(message, ChatMessage) @@ -222,11 +223,37 @@ export class MessageService { await this.save() } - async downloadFileMsg() { - const result = await this.NfService.beforeSendAttachment(this) - if(result) { + downloadFileMsg() { - } + let downloadFile = ""; + this.AttachmentsService.downloadFile(this.file.guid).subscribe(async (event) => { + + if (event.type === HttpEventType.DownloadProgress) { + + } else if (event.type === HttpEventType.Response) { + if (this.file.type == "application/img") { + downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); + } else if (this.file.type === 'application/pdf') { + + downloadFile = new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''); + console.log(downloadFile) + } else if (this.file.type == 'application/audio') { + downloadFile = new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''); + } + + this.attachments[0] = { + image_url: downloadFile, + name: this.attachments[0].name, + title: this.attachments[0].title, + title_link: downloadFile, + title_link_download: this.attachments[0].title_link_download, + ts: this.attachments[0].ts + } + + // save the changes to the storage + this.save() + } + }); } @@ -241,8 +268,7 @@ export class MessageService { } async delateDB() { - - // alert('delete data') + const message = await MessageModel.get({_id: this._id}) await message.delete() @@ -261,8 +287,8 @@ export class MessageService { return { channels: this.channels, mentions: this.mentions, - //msg: this.AESEncrypt.encrypt(this.msg, SessionStore.user.RochetChatUser), - msg:this.msg, + //msg: this.AESEncrypt.encrypt(this.msg, SessionStore.user.RochetChatUser), + msg:this.msg, rid: this.rid, ts: this.ts, u: this.u, @@ -294,6 +320,7 @@ export class MessageService { async save() { const message = this.getChatObj() + console.log(message); await MessageModel.update(message) diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index f7f9bbd7f..80fcab564 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -21,6 +21,8 @@ import { ChatMethodsService } from './chat-methods.service' import { DeleteMessageModel, MessageModel } from '../../models/beast-orm' import { AESEncrypt } from '../aesencrypt.service' import { IncomingChatMessage, ChatMessageInterface, falseTypingMethod } from 'src/app/models/message.model'; +import { AttachmentsService } from 'src/app/services/attachments.service'; +import { ConnectionStatus, NetworkServiceService} from 'src/app/services/network-service.service'; @Injectable({ providedIn: 'root' @@ -75,18 +77,17 @@ export class RoomService { private NfService: NfService, private ChatStorageService: ChatStorageService, private ChatMethodsService: ChatMethodsService, - private AESEncrypt: AESEncrypt + private AESEncrypt: AESEncrypt, + private AttachmentsService: AttachmentsService, + private NetworkServiceService: NetworkServiceService ) { this.NativeNotificationService.askForPermission() - // this.restoreMessageFromDB() - this.WsChatService.getUserStatus((d) => { const userId = d.fields.args[0][0] const statusNum = d.fields.args[0][2] const statusText = this.statusNumberToText(statusNum) - // if(this.members?.map) { const membersIds = this.members.map((user)=> user._id) @@ -143,7 +144,7 @@ export class RoomService { } } - setData({members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt), _updatedAt }) { + setData({members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService), _updatedAt }) { this.customFields = customFields this.id = id this.name = name @@ -236,7 +237,6 @@ export class RoomService { const args = message.fields.args - // alert(JSON.stringify(args)) if (typeof args[1] != 'object') { @@ -269,7 +269,12 @@ export class RoomService { getRoomMembersIds(): string[] { - return this.members.map((user)=> user._id) + try { + return this.members.map((user)=> user._id) + } catch(error) { + return [] + } + } getAllMemberThatIsNotOffline(): string[] { @@ -337,7 +342,6 @@ export class RoomService { } - async receiveMessageDelete() { this.WsChatService.updateRoomEventss( @@ -357,37 +361,42 @@ export class RoomService { * @description delete message in the view * @param id message ID */ - async deleteMessage(id) { - await this.messages.forEach(async(message, index) => { - if(message._id == id) { - - this.messages.splice(index, 1) - + async deleteMessage(_id) { + + const id = _id - if (SessionStore.user.RochetChatUser == message.u.username) { + for (let i =0; i <= this.messages.length; i++) { + + if(this.messages[i]?._id == id ) { + + + if (SessionStore.user.RochetChatUser == this.messages[i]?.u?.username) { const allMemberThatIsOffline = this.getAllMemberThatIsOffline() - await DeleteMessageModel.create({ - messageId: message._id, - rid: message.rid, - ts: message.ts, - u: message.u, + DeleteMessageModel.create({ + messageId: this.messages[i]._id, + rid: this.messages[i].rid, + ts: this.messages[i].ts, + u: this.messages[i].u, needToReceiveBy: allMemberThatIsOffline }) } - message.delateStatusFalse() - message.delateDB() + this.messages[i]?.delateDB() + this.messages.splice(i, 1) //Get previous last message from room const previousLastMessage = this.messages.slice(-1)[0]; - this.lastMessage = previousLastMessage; this.calDateDuration(previousLastMessage._updatedAt) this.sortRoomList() + return true + + } else { + // console.log(_id,'==',this.messages[i]?._id, false) } - }) + } } @@ -411,39 +420,31 @@ export class RoomService { async sendDeleteRequest(msgId) { - const message = this.messages.find((e)=>e._id = msgId) - message.delateStatusFalse() + const message = this.messages.find((e)=>e._id == msgId) + await message.delateStatusFalse() - this.ChatMethodsService.deleteMessage({_id:msgId, msgId:msgId, roomId:message.rid}).subscribe( - (response: any) => { + if(this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) { + + this.WsChatService.deleteMessage(msgId).then(async() => { message.delateRequest = true - message.save() + await message.save() this.deleteMessage(msgId) - }, - (response) => { + }) - if (response.error.error.startsWith('No message found with the id of')) { - // alert('not found') - this.deleteMessage(msgId) - } else { - // this.deleteMessage(DeletedMessageId) - this.WsChatService.registerCallback({ - type: 'reConnect', - funx: async ()=> { - - this.sendDeleteRequest(msgId) - return true - } - }) + } else { + this.WsChatService.registerCallback({ + type: 'reConnect', + funx: async ()=> { + + this.sendDeleteRequest(msgId) + return true } - - } - ) + }) + } } - /** * @description sen text message */ @@ -610,7 +611,7 @@ export class RoomService { await this.WsChatService.loadHistory(this.id, limit).then( async (chatHistory:chatHistory) => { - console.log('load chatHistory', JSON.stringify(chatHistory)) + // console.log('load chatHistory', JSON.stringify(chatHistory)) const messagesId = this.messages.map((message)=> message._id) @@ -666,7 +667,7 @@ export class RoomService { message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt) + const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService) wewMessage.setData(message) wewMessage.loadHistory = this.hasLoadHistory @@ -694,8 +695,6 @@ export class RoomService { } - - async ChatMessageIsPresentInTheView(ChatMessage:ChatMessageInterface) { let foundIndex; @@ -725,7 +724,7 @@ export class RoomService { async prepareCreate({message, save = true}): Promise { message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt) + const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService) wewMessage.setData(message) wewMessage.loadHistory = this.hasLoadHistory @@ -737,7 +736,7 @@ export class RoomService { simplePrepareMessage(message) { message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt) + const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService) wewMessage.setData(message) wewMessage.loadHistory = this.hasLoadHistory diff --git a/src/app/services/chat/ws-chat-methods.service.ts b/src/app/services/chat/ws-chat-methods.service.ts index 789d0a453..82dae5b98 100644 --- a/src/app/services/chat/ws-chat-methods.service.ts +++ b/src/app/services/chat/ws-chat-methods.service.ts @@ -19,6 +19,8 @@ import { AuthService } from '../auth.service'; import { ChatStorageService } from './chat-storage.service' import { ChatMethodsService } from './chat-methods.service' import { AESEncrypt } from '../aesencrypt.service' +import { AttachmentsService } from 'src/app/services/attachments.service'; +import { NetworkServiceService} from 'src/app/services/network-service.service'; @Injectable({ providedIn: 'root' @@ -55,7 +57,9 @@ export class WsChatMethodsService { private authService: AuthService, private ChatStorageService: ChatStorageService, private ChatMethodsService:ChatMethodsService, - private AESEncrypt: AESEncrypt + private AESEncrypt: AESEncrypt, + private AttachmentsService:AttachmentsService, + private NetworkServiceService: NetworkServiceService ) { this.loggedUser = authService.ValidatedUserChat['data']; @@ -158,7 +162,10 @@ export class WsChatMethodsService { } catch(e){} - this.sortRoomList() + setTimeout(()=>{ + this.sortRoomList() + }, 1000) + } async getAllRooms () { @@ -202,7 +209,11 @@ export class WsChatMethodsService { console.log('save rooms', rooms) await this.storage.set('Rooms', rooms); - this.sortRoomList() + + setTimeout(()=>{ + this.sortRoomList() + }, 1000) + this.loadingWholeList = false } @@ -305,7 +316,7 @@ export class WsChatMethodsService { // create room if(!this.roomExist(roomId)) { - let room:RoomService = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService , this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt) + let room:RoomService = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService , this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService) room.setData(setData) room.receiveMessage() room.getAllUsers = this.getUsers diff --git a/src/app/services/chat/ws-chat.service.ts b/src/app/services/chat/ws-chat.service.ts index 75df35da7..bfb47a6d9 100644 --- a/src/app/services/chat/ws-chat.service.ts +++ b/src/app/services/chat/ws-chat.service.ts @@ -728,7 +728,7 @@ export class WsChatService { this.wsMsgQueue[requestId] = {message, requestId, loginRequired} } else { let messageStr = JSON.stringify(message) - console.log('messageStr', messageStr) + // console.log('messageStr', messageStr) this.socket.send(messageStr) } diff --git a/src/app/services/functions/initials.service.spec.ts b/src/app/services/functions/initials.service.spec.ts new file mode 100644 index 000000000..7ecc24a60 --- /dev/null +++ b/src/app/services/functions/initials.service.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { InitialsService } from './initials.service'; + +describe('InitialsService', () => { + let service: InitialsService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(InitialsService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); diff --git a/src/app/services/functions/initials.service.ts b/src/app/services/functions/initials.service.ts new file mode 100644 index 000000000..3615f4124 --- /dev/null +++ b/src/app/services/functions/initials.service.ts @@ -0,0 +1,18 @@ +import { Injectable } from '@angular/core'; + +@Injectable({ + providedIn: 'root' +}) +export class InitialsService { + + constructor() { } + + getInitials(name:string){ + let names = name.split(' '), + initials = names[0].substring(0, 1).toUpperCase(); + if (names.length > 1) { + initials += names[names.length - 1].substring(0, 1).toUpperCase(); + } + return initials; + } +} diff --git a/src/app/services/network-service.service.spec.ts b/src/app/services/network-service.service.spec.ts new file mode 100644 index 000000000..987fc15ec --- /dev/null +++ b/src/app/services/network-service.service.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { NetworkServiceService } from './network-service.service'; + +describe('NetworkServiceService', () => { + let service: NetworkServiceService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(NetworkServiceService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); diff --git a/src/app/services/network-service.service.ts b/src/app/services/network-service.service.ts new file mode 100644 index 000000000..8e5e32d36 --- /dev/null +++ b/src/app/services/network-service.service.ts @@ -0,0 +1,62 @@ +import { Injectable } from '@angular/core'; +import { ToastController, Platform } from '@ionic/angular'; +import { BehaviorSubject, Observable } from 'rxjs'; +import { Network } from '@ionic-native/network/ngx' + + +export enum ConnectionStatus { + Online, + Offline +} + + +@Injectable({ + providedIn: 'root' +}) +export class NetworkServiceService { + private status: BehaviorSubject = new BehaviorSubject(ConnectionStatus.Offline); + + constructor(private network: Network, private toastController: ToastController, private plt: Platform) { + this.plt.ready().then(() => { + this.initializeNetworkEvents(); + let status = this.network.type !== 'none' ? ConnectionStatus.Online : ConnectionStatus.Offline; + this.status.next(status); + }); + + } + + public initializeNetworkEvents() { + + this.network.onDisconnect().subscribe(() => { + if (this.status.getValue() === ConnectionStatus.Online) { + this.updateNetworkStatus(ConnectionStatus.Offline); + } + }); + + this.network.onConnect().subscribe(() => { + if (this.status.getValue() === ConnectionStatus.Offline) { + this.updateNetworkStatus(ConnectionStatus.Online); + } + }); + } + + private async updateNetworkStatus(status: ConnectionStatus) { + this.status.next(status); + + let connection = status == ConnectionStatus.Offline ? 'Offline' : 'Online'; + let toast = this.toastController.create({ + message: `You are now ${connection}`, + duration: 3000, + position: 'bottom' + }); + toast.then(toast => toast.present()); + } + + public onNetworkChange(): Observable { + return this.status.asObservable(); + } + + public getCurrentNetworkStatus(): ConnectionStatus { + return this.status.getValue(); + } +} diff --git a/src/app/services/notifications.service.ts b/src/app/services/notifications.service.ts index f2c3d780d..afbefda73 100644 --- a/src/app/services/notifications.service.ts +++ b/src/app/services/notifications.service.ts @@ -86,86 +86,86 @@ export class NotificationsService { } requestPermissions() { - // PushNotifications.requestPermissions().then(result => { - // if (result.receive === 'granted') { - // // Register with Apple / Google to receive push via APNS/FCM - // PushNotifications.register(); - // } else { - // // Show some error - // } - // }); + PushNotifications.requestPermissions().then(result => { + if (result.receive === 'granted') { + // Register with Apple / Google to receive push via APNS/FCM + PushNotifications.register(); + } else { + // Show some error + } + }); } getAndpostToken(username) { - // if (this.platform.is('desktop') || this.platform.is('mobileweb')) { - // console.log('Notifications not supported') - // } else { - // const geturl = environment.apiURL + 'notifications/token'; - // PushNotifications.addListener('registration', - // (token: Token) => { - // console.log('token: ', token.value) - // this.storageService.store(username, token.value); - // this.storageService.get(username).then(value => { - // console.log('STORAGE TOKEN', value) - // this.storageService.get(AuthConnstants.USER).then(res => { - // console.log('USERID', res); - // const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; - // const body = { - // UserId: res.UserId, - // TokenId: token.value, - // Status: 1, - // Service: 1 - // }; + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + console.log('Notifications not supported') + } else { + const geturl = environment.apiURL + 'notifications/token'; + PushNotifications.addListener('registration', + (token: Token) => { + console.log('token: ', token.value) + this.storageService.store(username, token.value); + this.storageService.get(username).then(value => { + console.log('STORAGE TOKEN', value) + this.storageService.get(AuthConnstants.USER).then(res => { + console.log('USERID', res); + const headers = { 'Authorization': SessionStore.user.BasicAuthKey }; + const body = { + UserId: res.UserId, + TokenId: token.value, + Status: 1, + Service: 1 + }; - // this.http.post(`${geturl}`, body, { headers }).subscribe(data => { - // console.log('TOKEN USER MIDLE', data); - // }, (error) => { - // console.log('Post token to backend', error) - // }) - // }); + this.http.post(`${geturl}`, body, { headers }).subscribe(data => { + console.log('TOKEN USER MIDLE', data); + }, (error) => { + console.log('Post token to backend', error) + }) + }); - // }); - // } - // ); - // } + }); + } + ); + } } registrationError() { - // PushNotifications.addListener('registrationError', - // (error: any) => { - // console.log('Error on registration: ' + JSON.stringify(error)); - // } - // ); + PushNotifications.addListener('registrationError', + (error: any) => { + console.log('Error on registration: ' + JSON.stringify(error)); + } + ); } onReciveForeground() { - // PushNotifications.addListener('pushNotificationReceived', - // (notification: PushNotificationSchema) => { - // console.log('Push received: ' + JSON.stringify(notification)); - // this.DataArray.push(notification) - // console.log("On ReceiveNotification", this.DataArray) - // this.storageService.store("Notifications", this.DataArray) - // this.eventtrigger.publishSomeData({ - // notification: "recive" - // }) - // } - // ); + PushNotifications.addListener('pushNotificationReceived', + (notification: PushNotificationSchema) => { + console.log('Push received: ' + JSON.stringify(notification)); + this.DataArray.push(notification) + console.log("On ReceiveNotification", this.DataArray) + this.storageService.store("Notifications", this.DataArray) + this.eventtrigger.publishSomeData({ + notification: "recive" + }) + } + ); } onReciveBackground() { - // PushNotifications.addListener('pushNotificationActionPerformed', - // (notification: ActionPerformed) => { - // console.log('Push action performed: ' + JSON.stringify(notification)); - // /* this.DataArray.push(notification.notification) - // console.log("On ReceiveNotification", this.DataArray) - // this.storageService.store("Notifications", this.DataArray) - // this.eventtrigger.publishSomeData({ - // notification: "recive" - // }) */ - // this.notificatinsRoutes(notification) - // } - // ); + PushNotifications.addListener('pushNotificationActionPerformed', + (notification: ActionPerformed) => { + console.log('Push action performed: ' + JSON.stringify(notification)); + /* this.DataArray.push(notification.notification) + console.log("On ReceiveNotification", this.DataArray) + this.storageService.store("Notifications", this.DataArray) + this.eventtrigger.publishSomeData({ + notification: "recive" + }) */ + this.notificatinsRoutes(notification) + } + ); } tempClearArray() { @@ -175,51 +175,51 @@ export class NotificationsService { notificatinsRoutes = (notification) => { - // console.log('Push action performed 2222: ' + JSON.stringify(notification.data)); + console.log('Push action performed 2222: ' + JSON.stringify(notification.data)); - // if (notification.notification.data.Service === "agenda" && notification.notification.data.IdObject.length > 10) { - // console.log("Id Lenght", notification.notification.data.IdObject.length) - // this.zone.run(() => this.router.navigate(['/home/agenda', notification.notification.data.IdObject, 'agenda'])); - // } - // else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "expediente") { - // this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expediente', notification.notification.data.IdObject, 'gabinete-digital'])); - // } - // else if (notification.notification.data.Service === "agenda" && notification.notification.data.Object === "event-list") { - // //this.zone.run(() => this.router.navigate(['/home/gabinete-digital/event-list/approve-event',IdObject, 'agenda'])); - // this.zone.run(() => this.router.navigate(['/home/agenda/event-list/approve-event', notification.notification.data.IdObject, 'agenda'])); + if (notification.notification.data.Service === "agenda" && notification.notification.data.IdObject.length > 10) { + console.log("Id Lenght", notification.notification.data.IdObject.length) + this.zone.run(() => this.router.navigate(['/home/agenda', notification.notification.data.IdObject, 'agenda'])); + } + else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "expediente") { + this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expediente', notification.notification.data.IdObject, 'gabinete-digital'])); + } + else if (notification.notification.data.Service === "agenda" && notification.notification.data.Object === "event-list") { + //this.zone.run(() => this.router.navigate(['/home/gabinete-digital/event-list/approve-event',IdObject, 'agenda'])); + this.zone.run(() => this.router.navigate(['/home/agenda/event-list/approve-event', notification.notification.data.IdObject, 'agenda'])); - // } else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "despachos") { + } else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "despachos") { - // this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos', notification.notification.data.IdObject, 'gabinete-digital'], { replaceUrl: true })); - // } - // else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "parecer") { + this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos', notification.notification.data.IdObject, 'gabinete-digital'], { replaceUrl: true })); + } + else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "parecer") { - // this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', notification.notification.data.IdObject, 'gabinete-digital'])); - // } - // else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "deferimento") { + this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', notification.notification.data.IdObject, 'gabinete-digital'])); + } + else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "deferimento") { - // this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', notification.notification.data.IdObject, 'gabinete-digital'])); - // } - // else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "despachos-pr") { + this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos', notification.notification.data.IdObject, 'gabinete-digital'])); + } + else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "despachos-pr") { - // this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos-pr', notification.notification.data.IdObject, 'gabinete-digital'])); - // } - // else if (notification.notification.data.Service === "accoes" && notification.notification.data.Object === "accao") { - // this.zone.run(() => this.router.navigate(['/home/publications', notification.notification.data.IdObject])); - // } - // else if (notification.notification.data.Service === "accoes" && notification.notification.data.Object === "publicacao") { - // this.zone.run(() => this.router.navigate(['/home/publications/view-publications', notification.notification.data.FolderId, notification.data.IdObject])); - // } - // else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "diplomas") { - // this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas', notification.notification.data.IdObject, 'gabinete-digital'])); - // } - // else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "diplomas-assinar") { + this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos-pr', notification.notification.data.IdObject, 'gabinete-digital'])); + } + else if (notification.notification.data.Service === "accoes" && notification.notification.data.Object === "accao") { + this.zone.run(() => this.router.navigate(['/home/publications', notification.notification.data.IdObject])); + } + else if (notification.notification.data.Service === "accoes" && notification.notification.data.Object === "publicacao") { + this.zone.run(() => this.router.navigate(['/home/publications/view-publications', notification.notification.data.FolderId, notification.data.IdObject])); + } + else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "diplomas") { + this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas', notification.notification.data.IdObject, 'gabinete-digital'])); + } + else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "diplomas-assinar") { - // this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas-assinar', notification.notification.data.IdObject, 'gabinete-digital'])); - // } - // else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "expedientes-pr") { - // this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expedientes-pr', notification.notification.data.IdObject, 'gabinete-digital'])); - // } + this.zone.run(() => this.router.navigate(['/home/gabinete-digital/diplomas-assinar', notification.notification.data.IdObject, 'gabinete-digital'])); + } + else if (notification.notification.data.Service === "gabinete-digital" && notification.notification.data.Object === "expedientes-pr") { + this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expedientes-pr', notification.notification.data.IdObject, 'gabinete-digital'])); + } } diff --git a/src/app/services/permission.service.spec.ts b/src/app/services/permission.service.spec.ts index 8ddccabff..1a77304d8 100644 --- a/src/app/services/permission.service.spec.ts +++ b/src/app/services/permission.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed } from '@angular/core/testing'; -import { PermissionService } from './worker/permission.service'; +import { PermissionService } from './permission.service'; describe('PermissionService', () => { let service: PermissionService; diff --git a/src/app/services/permission.service.ts b/src/app/services/permission.service.ts new file mode 100644 index 000000000..b0ebcf48f --- /dev/null +++ b/src/app/services/permission.service.ts @@ -0,0 +1,58 @@ +import { Injectable } from '@angular/core'; +import { PermissionList } from '../models/permission/permissionList'; +import { SessionStore } from '../store/session.service'; + +@Injectable({ + providedIn: 'root' +}) +export class PermissionService { + + permissionList = new PermissionList(); + SessionStore = SessionStore + + constructor() { } + + userRole(args) { + + if(!Array.isArray(args)) { + args = [args] + } + + return args.includes(this.SessionStore.user.Profile) + } + + userPermission(args) { + if(!Array.isArray(args)) { + args = [args] + } + + + for(let permission of (this.SessionStore.user.UserPermissions || [])) { + if (args.includes(permission)) { + return true; + } + } + return false; + } + + role(args: any) { + + let UserRoleIsValid = this.userRole(args) + + return { + permissionAnyOf(role) { + + if(!Array.isArray(role)) { + role = [role] + } + + if(!UserRoleIsValid) { return false } + + return true + + } + } + + } + +} diff --git a/src/app/services/rules/event.service.ts b/src/app/services/rules/event.service.ts index c066e5223..a4f4e1be3 100644 --- a/src/app/services/rules/event.service.ts +++ b/src/app/services/rules/event.service.ts @@ -1,7 +1,7 @@ import { Injectable } from '@angular/core'; import { AttachmentsService } from '../attachments.service'; import { EventsService } from '../events.service'; -import { PermissionService } from '../worker/permission.service'; +import { PermissionService } from '../permission.service'; @@ -18,7 +18,7 @@ export class EventService { create({body, calendar}) { - + if(this.p.userRole(['PR'])) { return this.eventService.postEventPr(body, calendar) diff --git a/src/app/services/worker/permission.service.ts b/src/app/services/worker/permission.service.ts deleted file mode 100644 index e093625c9..000000000 --- a/src/app/services/worker/permission.service.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { Injectable } from '@angular/core'; -import { SessionStore } from '../../store/session.service'; - -@Injectable({ - providedIn: 'root' -}) -export class PermissionService { - - SessionStore = SessionStore - - constructor() { } - - userRole(args) { - - if(!Array.isArray(args)) { - args = [args] - } - - return args.includes(this.SessionStore.user.Profile) - } - - role(args: any) { - - let UserRoleIsValid = this.userRole(args) - - return { - permissionAnyOf(role) { - - if(!Array.isArray(role)) { - role = [role] - } - - if(!UserRoleIsValid) {return false } - - return true - - } - } - - } - -} \ No newline at end of file diff --git a/src/app/shared/chat/group-messages/group-messages.page.html b/src/app/shared/chat/group-messages/group-messages.page.html index 8032aa779..61ac8afd6 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.html +++ b/src/app/shared/chat/group-messages/group-messages.page.html @@ -60,66 +60,75 @@
-
-
-
-
- - - - -
-
- {{msg.u.name}} - {{msg.duration}} -
-
-
-
-
- image - -
-
-
-
- - - - - - - {{file.title}} +
+
+
+
+ + + + +
+
+ {{msg.u.name}} + {{msg.duration}} +
+
+
+
+
+ NOT UPLOADED +
+
+ image + +
+
+
+
+ + + + + + + {{file.title}} +
+
+ + + {{file.title}} + + + +
+
+ +
+
+ + {{file.description}} + + {{msg.displayType}} +
-
- -
-
- - {{file.description}} - - {{msg.displayType}} -
+ {{last ? scrollToBottom() : ''}}
- {{last ? scrollToBottom() : ''}}
+
+ {{msg.u.name}} criou esta reunião
+
+ De {{showDateDuration(msg.file.start_date)}} a {{showDateDuration(msg.file.end_date)}}
+ {{msg.file.venue}}
+
-
- {{msg.u.name}} criou esta reunião
-
- De {{showDateDuration(msg.file.start_date)}} a {{showDateDuration(msg.file.end_date)}}
- {{msg.file.venue}}
-
-
-
- Apagou a mensagem -
- +
Alterou o nome do grupo para "{{msg.msg.split('-').join(' ')}}"
diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index 245533836..283ddeefa 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -94,8 +94,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe allowTyping = true; storedFileNames = []; lastAudioRecorded = ''; - audioRecorded:any = ""; - audioDownloaded:any = ""; + audioRecorded: any = ""; + audioDownloaded: any = ""; durationDisplay = ''; duration = 0; @@ -142,7 +142,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe this.showAvatar = false - setTimeout(()=>{ + setTimeout(() => { this.scrollToBottomClicked() this.showAvatar = true }, 50) @@ -152,10 +152,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } ngOnInit() { - console.log(this.roomId); this.loggedUser = this.loggedUserChat; - - this.loggedUser=this.loggedUserChat; setTimeout(() => { this.getRoomInfo(); }, 1000); @@ -263,7 +260,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe }, 1000) } - async getFile(fileName?:any){ + async getFile(fileName?: any) { const audioFile = await Filesystem.readFile({ path: fileName, directory: Directory.Data @@ -274,20 +271,23 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } async loadFiles() { + try { + this.storage.get('fileName').then((fileName) => { + this.lastAudioRecorded = fileName; + }) + + this.storage.get('recordData').then((recordData) => { + console.log(recordData); + if (recordData?.value?.recordDataBase64.includes('data:audio')) { + this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(recordData?.value?.recordDataBase64); + } + else { + this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(`data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`); + } + }); + } catch (error) { } - this.storage.get('fileName').then((fileName) => { - this.lastAudioRecorded = fileName; - }) - this.storage.get('recordData').then((recordData) => { - console.log(recordData); - if(recordData.value.recordDataBase64.includes('data:audio')){ - this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(recordData.value.recordDataBase64); - } - else{ - this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(`data:${recordData.value.mimeType};base64,${recordData.value.recordDataBase64}`); - } - }); } startRecording() { @@ -317,8 +317,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe //console.log(recordData); const fileName = new Date().getTime() + ".mp3"; //Save file - this.storage.set('fileName',fileName); - this.storage.set('recordData',result).then(() => { + this.storage.set('fileName', fileName); + this.storage.set('recordData', result).then(() => { console.log('Audio recorded saved'); }) } @@ -328,7 +328,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe }, 1000); } - async deleteRecording(){ + async deleteRecording() { this.storage.remove('fileName'); this.storage.remove('recordData'); @@ -417,41 +417,64 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe this.wsChatMethodsService.getGroupRoom(this.roomId).send({}) } - async sendAudio(fileName) { + base64toBlob(base64Data, contentType) { + contentType = contentType || ''; + var sliceSize = 1024; + var byteCharacters = atob(base64Data); + var bytesLength = byteCharacters.length; + var slicesCount = Math.ceil(bytesLength / sliceSize); + var byteArrays = new Array(slicesCount); + for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) { + var begin = sliceIndex * sliceSize; + var end = Math.min(begin + sliceSize, bytesLength); + + var bytes = new Array(end - begin); + for (var offset = begin, i = 0; offset < end; ++i, ++offset) { + bytes[i] = byteCharacters[offset].charCodeAt(0); + } + byteArrays[sliceIndex] = new Uint8Array(bytes); + } + return new Blob(byteArrays, { type: contentType }); + } + + async sendAudio(fileName) { const roomId = this.roomId + let audioFile; this.storage.get('recordData').then((recordData) => { console.log(recordData); - if(recordData.value.recordDataBase64.includes('data:audio')){ - this.audioRecorded = recordData.value.recordDataBase64; + audioFile = recordData; + if (recordData?.value?.recordDataBase64.includes('data:audio')) { + this.audioRecorded = recordData?.value?.recordDataBase64; } - else{ - this.audioRecorded = `data:${recordData.value.mimeType};base64,${recordData.value.recordDataBase64}`; + else { + this.audioRecorded = `data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`; } + + + //Converting base64 to blob + const encodedData = btoa(this.audioRecorded); + const blob = this.base64toBlob(encodedData, recordData.value.mimeType) + console.log(blob) + const formData = new FormData(); + formData.append("blobFile", blob); + + this.wsChatMethodsService.getGroupRoom(roomId).send({ + file: { + "type": "application/audio", + "msDuration": audioFile.value.msDuration, + "mimeType": audioFile.value.mimeType, + }, + attachments: [{ + "title": fileName, + "title_link_download": true, + "type": "audio" + }], + temporaryData: formData + }) + }); - - //Converting base64 to blob - const base64Response = await fetch(this.audioRecorded); - const blob = await base64Response.blob(); - - const formData = new FormData(); - formData.append("blobFile", blob); - - this.wsChatMethodsService.getGroupRoom(roomId).send({ - file: { - "type": "application/audio", - /* "guid": '', */ - }, - attachments: [{ - "title": fileName , - "title_link": this.audioRecorded, - "title_link_download": true, - "type": "file" - }], - temporaryData: formData - }) this.deleteRecording(); - } deleteMessage(msgId: string) { @@ -701,7 +724,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe //const imageData = await this.fileToBase64Service.convert(file) //console.log('ADDFILECHAT', imageData) - const response = await fetch('data:image/jpeg;base64,'+ file.base64String!); + const response = await fetch('data:image/jpeg;base64,' + file.base64String!); const blob = await response.blob(); const formData = new FormData(); @@ -714,8 +737,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe }, temporaryData: formData, attachments: [{ - "title": file.path , - "image_url": 'data:image/jpeg;base64,' +file.base64String, + "title": file.path, + "image_url": 'data:image/jpeg;base64,' + file.base64String, "text": "description", "title_link_download": false, }] @@ -729,7 +752,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const image = await this.CameraService.takePicture(); await this.fileService.saveImage(image) const lastphoto: any = await this.fileService.loadFiles(); - const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); + const { capturedImage, capturedImageTitle } = await this.fileService.loadFileData(lastphoto); const base64 = await fetch(capturedImage); const blob = await base64.blob(); @@ -742,7 +765,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "guid": '' }, attachments: [{ - "title": capturedImageTitle , + "title": capturedImageTitle, "image_url": capturedImage, "text": "description", "title_link_download": false, @@ -773,13 +796,13 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } }); await modal.present(); - modal.onDidDismiss().then(async res=>{ + modal.onDidDismiss().then(async res => { const data = res.data; - if(data.selected) { + if (data.selected) { this.wsChatMethodsService.getGroupRoom(roomId).send({ - file:{ + file: { "name": res.data.selected.Assunto, "type": "application/webtrix", "ApplicationId": res.data.selected.ApplicationType, @@ -805,7 +828,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } }); } - async addFileToChatMobile(types: typeof FileType[] ) { + async addFileToChatMobile(types: typeof FileType[]) { const roomId = this.roomId const file = await Camera.getPhoto({ @@ -818,7 +841,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe //const imageData = await this.fileToBase64Service.convert(file) //console.log('ADDFILECHAT', imageData) - const response = await fetch('data:image/jpeg;base64,'+ file.base64String!); + const response = await fetch('data:image/jpeg;base64,' + file.base64String!); const blob = await response.blob(); const formData = new FormData(); @@ -831,8 +854,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe }, temporaryData: formData, attachments: [{ - "title": file.path , - "image_url": 'data:image/jpeg;base64,' +file.base64String, + "title": file.path, + "image_url": 'data:image/jpeg;base64,' + file.base64String, "text": "description", "title_link_download": false, }] @@ -841,39 +864,38 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } - async addFileToChat(types: typeof FileType[] ) { + async addFileToChat(types: typeof FileType[]) { const roomId = this.roomId const file: any = await this.fileService.getFileFromDevice(types); console.log('Add file', file) - /* const imageData = await this.fileToBase64Service.convert(file).then((filee) => { - console.log('Add file', filee) - }) */ - const blob = new Blob([file],{type: file.type}) - console.log('Add file', blob) - const formData = new FormData(); - formData.append("blobFile", blob); + if (file.type == "application/pdf") { + + const blob = new Blob([file], { type: file.type }) + console.log('Add file', blob) + + const formData = new FormData(); + formData.append("blobFile", blob); - let pdfBase64; - this.blobToBase64(blob).then(res => { - console.log('Base64 pdf', res); this.wsChatMethodsService.getGroupRoom(roomId).send({ file: { "type": file.type, "guid": '', }, attachments: [{ - "title": file.name , - "name": file.name , - "image_url": res, + "title": file.name, + "name": file.name, + /* "image_url": res, */ // "text": "description", "title_link_download": false, }], temporaryData: formData }) - }); + } else { + console.log('File type invalid') + } } @@ -932,7 +954,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } }); await modal.present(); - modal.onDidDismiss().then( async (res) => { + modal.onDidDismiss().then(async (res) => { console.log(res['data']); const roomId = this.roomId; @@ -971,54 +993,24 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe downloadFileMsg(msg: MessageService) { - console.log('FILE TYPE', msg.file.type) - this.downloadFile = ""; - if (msg.file.type == "application/img") { - this.AttachmentsService.downloadFile(msg.file.guid).subscribe(async (event) => { - console.log('FILE TYPE 22', msg.file.guid) - var name = msg.file.guid; - - if (event.type === HttpEventType.DownloadProgress) { - //this.downloadProgess = Math.round((100 * event.loaded) / event.total); - console.log('FILE TYPE 33', msg.file.type) - } else if (event.type === HttpEventType.Response) { - if (msg.file.type == "application/img") { - this.downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); - } else if (msg.file.type === 'application/pdf') { - - this.downloadFile = event.body; - } - - msg.attachments[0] = { - image_url: this.downloadFile, - name: msg.attachments[0].name, - title: msg.attachments[0].title, - title_link_download: msg.attachments[0].title_link_download, - ts: msg.attachments[0].ts - } - - await this.storage.set(msg.file.guid, this.downloadFile).then(() => { - console.log('IMAGE SAVED') - }); - } - - }); - - } - + msg.downloadFileMsg() } async openPreview(msg) { - if (!msg.attachments[0].image_url || msg.attachments[0].image_url === null || msg.attachments[0].image_url === '' ) { + if (!msg.attachments[0].image_url || msg.attachments[0].image_url === null || msg.attachments[0].image_url === '') { this.downloadFileMsg(msg) } else { + + var str = msg.attachments[0].image_url; + str = str.substring(1, ((str.length) - 1)); + const modal = await this.modalController.create({ component: ViewMediaPage, cssClass: 'modal modal-desktop', componentProps: { - image: msg.attachments[0].image_url, + image: str, type: msg.file.type, username: msg.u.name, _updatedAt: msg._updatedAt @@ -1029,5 +1021,12 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } + async audioPreview(msg) { + console.log(msg); + if (!msg.attachments[0].title_link || msg.attachments[0].title_link === null || msg.attachments[0].title_link === '') { + this.downloadFileMsg(msg) + } else { } + } + } diff --git a/src/app/shared/chat/messages/messages.page.html b/src/app/shared/chat/messages/messages.page.html index f2b691ed3..8b88fc645 100644 --- a/src/app/shared/chat/messages/messages.page.html +++ b/src/app/shared/chat/messages/messages.page.html @@ -35,7 +35,7 @@
+ *ngFor="let msg of wsChatMethodsService.getDmRoom(roomId).messages; index as i; let last = last">
@@ -49,12 +49,12 @@ {{msg.duration}}
- - {{msg.msg}} + + {{msg.msg}} Apagou a mensagem - + @@ -84,7 +84,6 @@
image - @@ -109,7 +108,15 @@ {{file.title}}
-
+
+ + + {{file.title}} + + + +
+
@@ -119,7 +126,7 @@ {{msg.displayType}} - + @@ -133,28 +140,30 @@
- {{msg.u.name}} criou esta reunião
-
- + De {{showDateDuration(msg.file.start_date)}} a {{showDateDuration(msg.file.end_date)}}
- + {{msg.file.venue}}
-
- Apagou a mensagem -
+
- + @@ -165,7 +174,7 @@ - +
{ + this.lastAudioRecorded = fileName; + }) + + this.storage.get('recordData').then((recordData) => { + console.log(recordData); + if (recordData?.value?.recordDataBase64.includes('data:audio')) { + this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(recordData?.value?.recordDataBase64); + } + else { + this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(`data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`); + } + }); + } catch (error) { } - this.storage.get('fileName').then((fileName) => { - this.lastAudioRecorded = fileName; - }) this.storage.get('recordData').then((recordData) => { console.log(recordData); - if(recordData.value.recordDataBase64.includes('data:audio')){ + if (recordData.value.recordDataBase64.includes('data:audio')) { this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(recordData.value.recordDataBase64); } - else{ + else { this.audioRecorded = this.sanitiser.bypassSecurityTrustResourceUrl(`data:${recordData.value.mimeType};base64,${recordData.value.recordDataBase64}`); } }); } startRecording() { - console.log('Recording'); if (this.recording) { return; @@ -293,8 +303,8 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy //console.log(recordData); const fileName = new Date().getTime() + ".mp3"; //Save file - this.storage.set('fileName',fileName); - this.storage.set('recordData',result).then(() => { + this.storage.set('fileName', fileName); + this.storage.set('recordData', result).then(() => { console.log('Audio recorded saved'); }) } @@ -304,7 +314,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy }, 1000); } - async deleteRecording(){ + async deleteRecording() { this.storage.remove('fileName'); this.storage.remove('recordData'); @@ -354,81 +364,92 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy this.wsChatMethodsService.getDmRoom(this.roomId).send({}) } - async sendAudio(fileName) { + async sendAudio(fileName) { const roomId = this.roomId let audioFile; this.storage.get('recordData').then((recordData) => { console.log(recordData); audioFile = recordData; - if(recordData.value.recordDataBase64.includes('data:audio')){ + + if (recordData.value.recordDataBase64.includes('data:audio')) { this.audioRecorded = recordData.value.recordDataBase64; } - else{ - this.audioRecorded = `data:${recordData.value.mimeType};base64,${recordData.value.recordDataBase64}`; + else { + this.audioRecorded = `data:${recordData.value.mimeType};base64,${recordData?.value?.recordDataBase64}`; } + //Converting base64 to blob + const encodedData = btoa(this.audioRecorded); + const blob = this.base64toBlob(encodedData, recordData.value.mimeType) + console.log(blob) + const formData = new FormData(); + formData.append("blobFile", blob); + + this.wsChatMethodsService.getDmRoom(roomId).send({ + file: { + "type": "application/audio", + "msDuration": audioFile.value.msDuration, + "mimeType": audioFile.value.mimeType, + }, + attachments: [{ + "title": fileName, + "title_link_download": true, + "type": "audio" + }], + temporaryData: formData + }) + }); - - //Converting base64 to blob - const base64Response = await fetch(this.audioRecorded); - const blob = await base64Response.blob(); - - const formData = new FormData(); - formData.append("blobFile", blob); - - this.wsChatMethodsService.getDmRoom(roomId).send({ - file: { - "type": "application/audio", - /* "guid": '', */ - "msDuration":audioFile.value.msDuration, - "mimeType":audioFile.value.mimeType, - }, - attachments: [{ - "title": fileName , - "title_link": this.audioRecorded, - "title_link_download": true, - "type": "audio" - }], - temporaryData: formData - }) this.deleteRecording(); - } - deleteMessage(msgId: string, msg:MessageService) { - msg.delateStatusFalse() + deleteMessage(msgId: string, msg: MessageService) { this.wsChatMethodsService.getDmRoom(this.roomId).sendDeleteRequest(msgId) - - } - - async viewDocument(msg: any, url?: string) { - if (msg.file.type == "application/img") { - let response: any = await this.AttachmentsService.getFile(msg.file.guid).toPromise(); - console.log(response); - alert(response); - - //this.openPreview(msg); - - } - else if (msg.file.type == "application/webtrix") { + if (msg.file.type == "application/webtrix") { this.openViewDocumentModal(msg.file); } else { console.log('PDF CLICK', msg) + var str = msg.attachments[0].image_url; + str = str.substring(1, ((str.length) - 1)); + + const encodedData = btoa(str); /* let fullUrl; fullUrl = "https://gabinetedigitalchat.dyndns.info" + url; //fullUrl = "http://www.africau.edu/images/default/sample.pdf"; this.frameUrl = fullUrl; */ - let file = new Blob([msg.attachments[0].image_url], { type: 'application/pdf' }); + let file = this.base64toBlob(encodedData, 'application/pdf') let fileURL = URL.createObjectURL(file) + console.log('PDF CLICK', fileURL) window.open(fileURL); // this.chatService.getDocumentDetails(fullUrl); } } + base64toBlob(base64Data, contentType) { + contentType = contentType || ''; + var sliceSize = 1024; + var byteCharacters = atob(base64Data); + var bytesLength = byteCharacters.length; + var slicesCount = Math.ceil(bytesLength / sliceSize); + var byteArrays = new Array(slicesCount); + + for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) { + var begin = sliceIndex * sliceSize; + var end = Math.min(begin + sliceSize, bytesLength); + + var bytes = new Array(end - begin); + for (var offset = begin, i = 0; offset < end; ++i, ++offset) { + bytes[i] = byteCharacters[offset].charCodeAt(0); + } + byteArrays[sliceIndex] = new Uint8Array(bytes); + } + return new Blob(byteArrays, { type: contentType }); + } + async openViewDocumentModal(file: any) { let task = { @@ -747,19 +768,18 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy const file: any = await this.fileService.getFileFromDevice(types); - console.log('Add file', file) - /* const imageData = await this.fileToBase64Service.convert(file).then((filee) => { - console.log('Add file', filee) - }) */ - const blob = new Blob([file], { type: file.type }) - console.log('Add file', blob) + if (file.type == "application/pdf") { - const formData = new FormData(); - formData.append("blobFile", blob); + console.log('Add file', file) + /* const imageData = await this.fileToBase64Service.convert(file).then((filee) => { + console.log('Add file', filee) + }) */ + const blob = new Blob([file], { type: file.type }) + console.log('Add file', blob) + + const formData = new FormData(); + formData.append("blobFile", blob); - let pdfBase64; - this.blobToBase64(blob).then(res => { - //console.log('Base64 pdf', res); this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": file.type, @@ -774,7 +794,10 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy }], temporaryData: formData }) - }); + + } else { + console.log('File type invalid') + } } @@ -882,54 +905,9 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy downloadFileMsg(msg: MessageService) { - console.log('FILE TYPE', msg.file.type) - this.downloadFile = ""; - //if (msg.file.type == "application/img") { - this.AttachmentsService.downloadFile(msg.file.guid).subscribe(async (event) => { - console.log('FILE TYPE 22', msg.file.guid) - var name = msg.file.guid; - - if (event.type === HttpEventType.DownloadProgress) { - //this.downloadProgess = Math.round((100 * event.loaded) / event.total); - console.log('FILE TYPE 33', msg.file.type) - } else if (event.type === HttpEventType.Response) { - if (msg.file.type == "application/img") { - this.downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); - } else if (msg.file.type === 'application/pdf') { - - this.downloadFile = event.body; - } - - msg.attachments[0] = { - image_url: this.downloadFile, - name: msg.attachments[0].name, - title: msg.attachments[0].title, - title_link_download: msg.attachments[0].title_link_download, - ts: msg.attachments[0].ts - } - - // save the changes to the storage - msg.save() - - - } - - }); - - // } - + msg.downloadFileMsg() } - _arrayBufferToBase64( buffer ) { - var binary = ''; - var bytes = new Uint8Array( buffer ); - var len = bytes.byteLength; - for (var i = 0; i < len; i++) { - binary += String.fromCharCode( bytes[ i ] ); - } - return window.btoa( binary ); -} - pdfPreview() { const options: DocumentViewerOptions = { title: 'My App' @@ -937,14 +915,45 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy DocumentViewer.viewDocument } + async audioPreview(msg) { + console.log(msg); + if (!msg.attachments[0].title_link || msg.attachments[0].title_link === null || msg.attachments[0].title_link === '') { + this.downloadFileMsg(msg) + } else { } + } + async openPreview(msg) { console.log(msg); if (!msg.attachments[0].image_url || msg.attachments[0].image_url === null || msg.attachments[0].image_url === '') { this.downloadFileMsg(msg) + + /* } else if (msg.file.type === "application/pdf") { + + + console.log(str); + const win = window.open("", "_blank"); + let html = ''; + + html += ''; + html += ''; + html += '