From 26b894ed1c4e20ef5884e5fe6c3ac03bf7a42f6d Mon Sep 17 00:00:00 2001 From: Lorito Tiago <58330997+LoritoTiago@users.noreply.github.com> Date: Thu, 19 Oct 2023 15:03:12 +0100 Subject: [PATCH] fix chat open modal --- ios/App/App.xcodeproj/project.pbxproj | 4 +- src/app/pages/chat/chat.page.ts | 53 +- .../group-messages/group-messages.page.html | 247 +++++--- .../group-messages/group-messages.page.ts | 2 + .../pages/chat/messages/messages.page.html | 194 ++++--- src/app/pages/chat/messages/messages.page.ts | 83 +-- src/app/services/chat/chat-system.service.ts | 236 +++----- .../chat/rochet-chat-connector.service.ts | 531 ++++++++++-------- src/app/services/chat/room.service.ts | 361 ++++++------ src/app/services/notifications.service.ts | 10 +- src/app/store/notification-holder.service.ts | 86 ++- 11 files changed, 976 insertions(+), 831 deletions(-) diff --git a/ios/App/App.xcodeproj/project.pbxproj b/ios/App/App.xcodeproj/project.pbxproj index d1eb09c1b..1e860d85a 100644 --- a/ios/App/App.xcodeproj/project.pbxproj +++ b/ios/App/App.xcodeproj/project.pbxproj @@ -390,7 +390,7 @@ CODE_SIGN_ENTITLEMENTS = App/App.entitlements; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 47; + CURRENT_PROJECT_VERSION = 61; DEVELOPMENT_TEAM = ""; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = 94BRNM2LSS; INFOPLIST_FILE = App/Info.plist; @@ -419,7 +419,7 @@ CODE_SIGN_ENTITLEMENTS = App/App.entitlements; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 47; + CURRENT_PROJECT_VERSION = 61; DEVELOPMENT_TEAM = ""; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = 94BRNM2LSS; INFOPLIST_FILE = App/Info.plist; diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index c51a358d1..5008e5e01 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -30,7 +30,7 @@ import { SessionStore } from 'src/app/store/session.service'; import { ChatDebuggingPage } from 'src/app/shared/popover/chat-debugging/chat-debugging.page'; import { EventTrigger } from 'src/app/services/eventTrigger.service'; import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; - +import { RouteService } from 'src/app/services/route.service'; import { Plugins } from '@capacitor/core'; const { App } = Plugins; @@ -126,7 +126,8 @@ export class ChatPage implements OnInit { private activatedRoute: ActivatedRoute, private eventTriger: EventTrigger, private RochetChatConnectorService: RochetChatConnectorService, - private zone: NgZone + private zone: NgZone, + public RouteService: RouteService, ) { this.headers = new HttpHeaders(); @@ -174,7 +175,6 @@ export class ChatPage implements OnInit { } }); - this.routeCheck() } ngOnDestroy() { @@ -189,14 +189,45 @@ export class ChatPage implements OnInit { // Retry connecting or other reconnection logic can be added here. } - routeCheck() { + firstEnter = true + routeCheck() { const urlParams = new URLSearchParams(window.location.search); const roomId = urlParams.get('roomId'); if (roomId) { - const room = this.ChatSystemService.getRoomById(roomId); + if (this.firstEnter) { + this.firstEnter = false + + let delay = this.RouteService.history.find((item) => { + return ['/home/publications', '/home/agenda', '/home/gabinete', '/home/events'].filter(x => { + return item.includes(x) + }).length >= 1 + }) + if (!delay) { + console.log("delay") + setTimeout(() => { + this.openChat(roomId) + }, 2000) + } else { + console.log("no dalay") + this.openChat(roomId) + } + } else { + this.openChat(roomId) + } + + + } + + } + + openFailed = 0 + openChat(roomId) { + const room = this.ChatSystemService.getRoomById(roomId); + if (room) { + this.openFailed = 0 if (room.isGroup) { this.segment = 'Grupos' this.openGroupMessagesPage(roomId) @@ -204,8 +235,17 @@ export class ChatPage implements OnInit { this.segment = 'Contactos' this.openMessagesPage(roomId) } - } + } else { + if (this.openFailed <= 3) { + this.openFailed++ + setTimeout(() => { + this.openChat(roomId) + }, 1000) + } else { + this.openFailed = 0 + } + } } @@ -751,7 +791,6 @@ export class ChatPage implements OnInit { }); modal.onDidDismiss().then((Data) => { - // console.log(Data,'daatatatat'); // let data = Data.data // let roomId = data.roomId diff --git a/src/app/pages/chat/group-messages/group-messages.page.html b/src/app/pages/chat/group-messages/group-messages.page.html index 75811ab21..83fcbe6bf 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.html +++ b/src/app/pages/chat/group-messages/group-messages.page.html @@ -1,4 +1,4 @@ - +
@@ -19,7 +19,7 @@
@@ -27,10 +27,11 @@
- +
- + {{member.name}},
@@ -39,6 +40,7 @@ {{roomCountDownDate}}
+ {{ RouteService.history }}
@@ -51,24 +53,31 @@ Esta conversa passou a grupo
A conversa original mantêm-se como chat individual -
-
+
+
{{msg.u.name ?? ""}} {{msg.time}}
-
{{msg.msg}}
-
{{msg.msg}}
+
{{msg.msg}}
+
{{msg.msg}}
- Enviado + + Enviado - Lido + Lido
Tentar
{{last ? scrollToBottom() : ''}} @@ -77,78 +86,115 @@
-
-
- {{msg.u.name ?? ""}} - {{msg.time}} -
-
-
-
-
- NOT UPLOADED -
-
-
- - - {{"Imagem"}} - - - - +
+
+ {{msg.u.name ?? ""}} + {{msg.time}} +
+
+
+
+
+ NOT UPLOADED
- image - - - Enviado - - - - - Lido -
Tentar
-
-
-
+
+
+ + + {{"Imagem"}} + + + + +
+ image + + + + Enviado + + + + + Lido +
Tentar
+
+
+
- - + + {{ file.title}} - - - + + +
- - - - - - - - {{file.title}} -
+ + + + + + + + {{file.title}} +
-
+
{{"Mensagem de voz"}} - - - + + +
- +
@@ -158,27 +204,31 @@ - Enviado + + Enviado - Lido + Lido
Tentar
+
+ {{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}}
+
@@ -209,9 +259,9 @@
{{last ? scrollToBottom() : ''}}
-
+
-
+
Adicionou {{user.name}}
@@ -231,24 +281,24 @@
- + {{ ChatSystemService.getGroupRoom(roomId).userThatIsTyping }} está a escrever...
{{durationDisplay}} - +
- +
- -
-
+ \ No newline at end of file diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index 336508ec1..e243c7405 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -31,6 +31,7 @@ import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx'; import { SessionStore } from 'src/app/store/session.service'; import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { Camera, CameraResultType, CameraSource } from '@capacitor/camera'; +import { RouteService } from 'src/app/services/route.service'; @Component({ selector: 'app-group-messages', templateUrl: './group-messages.page.html', @@ -102,6 +103,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { private sanitiser: DomSanitizer, private file: File, private fileOpener: FileOpener, + public RouteService: RouteService, ) { this.ChatSystemService.getUser() diff --git a/src/app/pages/chat/messages/messages.page.html b/src/app/pages/chat/messages/messages.page.html index f7ab9fe1d..2d5982a83 100644 --- a/src/app/pages/chat/messages/messages.page.html +++ b/src/app/pages/chat/messages/messages.page.html @@ -1,4 +1,4 @@ - +
@@ -11,7 +11,8 @@
{{ChatSystemService.getDmRoom(roomId).name}} - +
@@ -41,116 +42,150 @@ - +
-
-
+
- {{msg.u.name}} + {{msg.u.name}} {{msg.time}}
-
+
-
{{msg.msg}}
- - Apagou a mensagem +
{{msg.msg}}
+ + Apagou a mensagem - + - Enviado - - - - - Lido -
Tentar
-
-
+ + Enviado + + + + + Lido +
Tentar
+ +
{{last ? scrollToBottom() : ''}}
-
-
- {{msg.u.name}} - {{msg.time}} -
-
-
-
-
-
- - - {{"Imagem"}} - - - - +
+
+ {{msg.u.name}} + {{msg.time}} +
+
+
+
+
+
+ + + {{"Imagem"}} + + + + +
+ image + + + + Enviado + + + + + Lido +
Tentar
+
+
- image - - - Enviado - - - - - Lido -
Tentar
-
- -
-
+
-
+
- - + + {{ file.title}} - - - + + +
- - - - - - - - - - {{file.title}} + + + + + + + + + + {{file.title}}
-
+
{{"Mensagem de voz"}} - - - + + +
@@ -166,12 +201,13 @@ - Enviado + + Enviado - Lido + Lido
Tentar
@@ -213,7 +249,7 @@ - +
-
+
\ No newline at end of file diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 36bb6c5d8..3a42df267 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -118,39 +118,50 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { private router: Router, public RochetChatConnectorService: RochetChatConnectorService, ) { - this.loggedUser = SessionStore.user.ChatData['data']; - this.roomId = this.navParams.get('roomId'); + + try { + + this.loggedUser = SessionStore.user.ChatData['data']; + this.roomId = this.navParams.get('roomId'); - window.onresize = (event) => { - if (window.innerWidth > 701) { - this.modalController.dismiss(); + window.onresize = (event) => { + if (window.innerWidth > 701) { + this.modalController.dismiss(); + } } + + + this.ChatSystemService.getDmRoom(this.roomId).loadHistory({}) + this.ChatSystemService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked + this.ChatSystemService.openRoom(this.roomId) + + setTimeout(() => { + this.scrollToBottomClicked() + }, 150) + } catch (error) { + //alert(error) } - this.ChatSystemService.getDmRoom(this.roomId).loadHistory({}) - this.ChatSystemService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked - this.ChatSystemService.openRoom(this.roomId) - - setTimeout(() => { - this.scrollToBottomClicked() - }, 150) - - } ngOnInit() { - console.log(this.router.url); - this.createDirectoryImage() - // this.chatService.refreshtoken(); - this.ChatSystemService.getUserOfRoom(this.roomId).then((value) => { + try { + console.log(this.router.url); + this.createDirectoryImage() + // this.chatService.refreshtoken(); + this.ChatSystemService.getUserOfRoom(this.roomId).then((value) => { - }).catch((error) => { - console.error(error) - }) + }).catch((error) => { + console.error(error) + }) + + this.getChatMembers(); + } catch (error) { + //alert(error) + } - this.getChatMembers(); } @@ -175,8 +186,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { longpress.enable(); } - onDragOver(e?) {} - onDragLeave(e?) {} + onDragOver(e?) { } + onDragLeave(e?) { } calculateDuration() { if (!this.recording) { @@ -668,7 +679,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } - dataURItoBlob(dataURI) { + dataURItoBlob(dataURI) { // convert base64 to raw binary data held in a string // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this var byteString = atob(dataURI.split(',')[1]); @@ -684,11 +695,11 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { // set the bytes of the buffer to the correct values for (var i = 0; i < byteString.length; i++) { - ia[i] = byteString.charCodeAt(i); + ia[i] = byteString.charCodeAt(i); } // write the ArrayBuffer to a blob, and you're done - var blob = new Blob([ab], {type: mimeString}); + var blob = new Blob([ab], { type: mimeString }); return blob; } @@ -810,7 +821,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { _getBase64(file) { - return new Promise((resolve, reject)=>{ + return new Promise((resolve, reject) => { var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { @@ -820,7 +831,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { console.log('Error: ', error); }; }) - } + } async addFileToChat(types: typeof FileType[]) { console.log('add file') @@ -844,18 +855,18 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { if (file.type != "application/img" && file.type != "image/png" && file.type != "image/jpeg" && file.type != "image/gif") { - console.log('TYPE',file.type) + console.log('TYPE', file.type) - const encodedData = btoa(JSON.stringify(await this.getBase64(file).catch ((error) => { + const encodedData = btoa(JSON.stringify(await this.getBase64(file).catch((error) => { console.error(error); }))); console.log(encodedData) const blob = this.fileService.base64toBlob(encodedData, file.type) - console.log('BLOB BLOB',blob) + console.log('BLOB BLOB', blob) const formData = new FormData(); formData.append('blobFile', blob); - /* console.log('add file', fileBase64) */ + /* console.log('add file', fileBase64) */ this.ChatSystemService.getDmRoom(roomId).send({ file: { @@ -1065,9 +1076,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { }).then((dir) => { console.log('DIR ', dir) this.fileOpener - .open(dir.uri, type) - .then(() => console.log()) - .catch(e => console.error(e)) + .open(dir.uri, type) + .then(() => console.log()) + .catch(e => console.error(e)) }); } diff --git a/src/app/services/chat/chat-system.service.ts b/src/app/services/chat/chat-system.service.ts index d11195030..39739c0cc 100644 --- a/src/app/services/chat/chat-system.service.ts +++ b/src/app/services/chat/chat-system.service.ts @@ -114,7 +114,10 @@ export class ChatSystemService { document.addEventListener('resume', () => { this.RochetChatConnectorService.setStatus('online') if (this._dm?.length == 0 && this._group?.length == 0) { - this.getAllRooms(); + if (SessionStore.user?.ChatData?.data) { + this.getAllRooms(); + } + } }); @@ -124,11 +127,15 @@ export class ChatSystemService { // The app is in the foreground. console.log('App is in the foreground'); - this.currentRoom?.loadHistory({ forceUpdate: true }) + if (SessionStore.user?.ChatData?.data) { + this.currentRoom?.loadHistory({ forceUpdate: true }) + } setTimeout(() => { - this.subscribeToRoom() - this.RochetChatConnectorService.setStatus('online') + if (SessionStore.user?.ChatData?.data) { + this.subscribeToRoom() + this.RochetChatConnectorService.setStatus('online') + } }, 1000); /* this.reloadComponent(true) */ @@ -150,15 +157,16 @@ export class ChatSystemService { private async ReLoadChat() { - this.getUserStatus(); - await this.chatService.refreshtoken(); - - this.restoreUsers(); - await this.getUser(); - await this.restoreRooms(); - await this.getAllRooms(); - this.subscribeToRoom(); + if (SessionStore.user?.ChatData?.data) { + this.getUserStatus(); + await this.chatService.refreshtoken(); + this.restoreUsers(); + await this.getUser(); + await this.restoreRooms(); + await this.getAllRooms(); + this.subscribeToRoom(); + } // } @@ -263,90 +271,23 @@ export class ChatSystemService { for (let roomData of this.sortArrayISODate(_rooms)) { - const roomId = this.getRoomId(roomData); if (roomData.t == 'd') { - - let error = false - let res; - - try { - res = await this.chatService.getMembers(roomId).toPromise(); - } catch (e) { - await this.chatService.refreshtoken(); - error = true - } - - if (error) { - res = await this.chatService.getMembers(roomId).toPromise(); - } - - - const members = res['members']; - const users = members.filter(data => data.username != this.sessionStore.user.UserName); - _rooms[index]['members'] = members - _rooms[index]['membersExcludeMe'] = users - await this.prepareRoom(roomData); } else { if (roomData.t === 'p') { - let error = false - let res; - - try { - res = await this.chatService.getGroupMembers(roomId).toPromise() - } catch (e) { - await this.chatService.refreshtoken(); - error = true - } - - if (error) { - res = await this.chatService.getGroupMembers(roomId).toPromise() - } - - const members = res['members']; - const users = members.filter(data => data.username != this.sessionStore.user.UserName); - - _rooms[index]['members'] = members - _rooms[index]['membersExcludeMe'] = users - await this.prepareRoom(roomData); - } else { - - let error = false - let res; - - try { - res = await this.chatService.getChannelMembers(roomId).toPromise() - - } catch (e) { - await this.chatService.refreshtoken(); - error = true - } - - if (error) { - res = await this.chatService.getChannelMembers(roomId).toPromise() - } - - - const members = res['members']; - const users = members.filter(data => data.username != this.sessionStore.user.UserName); - - _rooms[index]['members'] = members - _rooms[index]['membersExcludeMe'] = users await this.prepareRoom(roomData); } - } if (roomId == roomIdCallback) { callback() } - index++; } } @@ -362,7 +303,6 @@ export class ChatSystemService { async getRoom(_rooms: any) { this.loadingWholeList = true - let index = 0 if (_rooms) { @@ -374,80 +314,17 @@ export class ChatSystemService { for (let roomData of this.sortArrayISODate(_rooms)) { - - const roomId = this.getRoomId(roomData); - if (roomData.t == 'd') { - let error = false - let res; - - try { - res = await this.chatService.getMembers(roomId).toPromise(); - } catch (e) { - await this.chatService.refreshtoken(); - error = true - } - - if (error) { - res = await this.chatService.getMembers(roomId).toPromise(); - } - - - const members = res['members']; - const users = members.filter(data => data.username != this.sessionStore.user.UserName); - _rooms[index]['members'] = members - _rooms[index]['membersExcludeMe'] = users - await this.prepareRoom(roomData); } else { if (roomData.t === 'p') { - let error = false - let res; - - try { - res = await this.chatService.getGroupMembers(roomId).toPromise() - } catch (e) { - await this.chatService.refreshtoken(); - error = true - } - - if (error) { - res = await this.chatService.getGroupMembers(roomId).toPromise() - } - - const members = res['members']; - const users = members.filter(data => data.username != this.sessionStore.user.UserName); - - _rooms[index]['members'] = members - _rooms[index]['membersExcludeMe'] = users await this.prepareRoom(roomData); } else { - let error = false - let res; - - try { - res = await this.chatService.getChannelMembers(roomId).toPromise() - - } catch (e) { - await this.chatService.refreshtoken(); - error = true - } - - if (error) { - res = await this.chatService.getChannelMembers(roomId).toPromise() - } - - - const members = res['members']; - const users = members.filter(data => data.username != this.sessionStore.user.UserName); - - _rooms[index]['members'] = members - _rooms[index]['membersExcludeMe'] = users await this.prepareRoom(roomData); } @@ -477,17 +354,26 @@ export class ChatSystemService { */ subscribeToRoom() { - for (const id in this.dm) { - this.defaultSubtribe(id) + if (SessionStore.user?.ChatData?.data) { + + for (const id in this.dm) { + this.defaultSubtribe(id) + } + + for (const id in this.group) { + this.defaultSubtribe(id) + } + + this.RochetChatConnectorService.streamNotifyLogged().then((subscription => { })) + + this.RochetChatConnectorService.subStreamMessageUser().then((subscription => { })) + } else { + + setTimeout(() => { + throw ('No chat data'); + }, 1000) } - for (const id in this.group) { - this.defaultSubtribe(id) - } - - this.RochetChatConnectorService.streamNotifyLogged().then((subscription => { })) - - this.RochetChatConnectorService.subStreamMessageUser().then((subscription => { })) } /** @@ -576,13 +462,20 @@ export class ChatSystemService { lastMessage: this.getRoomLastMessage(roomData), _updatedAt: new Date(roomData._updatedAt || roomData._updatedAt['$date']), u: roomData.u || {}, - members: roomData.members, - membersExcludeMe: roomData.membersExcludeMe + members: [], + membersExcludeMe: [] } let roomId = this.getRoomId(roomData); - if (setData.name != 'Rocket Cat' && setData.name != 'general') { + let chat = false + if (roomData?.usernames) { + if (roomData?.usernames?.includes("chat.admin")) { + chat = true + } + } + + if (setData.name != 'Rocket Cat' && setData.name != 'general' && chat == false) { // create room if (!this.roomExist(roomId)) { let room: RoomService = new RoomService(this.RochetChatConnectorService, new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this, this.notificationService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this, this.ViewedMessageService, this.notificationService) @@ -755,26 +648,33 @@ export class ChatSystemService { getRoomName(roomData: room): string { if (this.isIndividual(roomData)) { const names: String[] = roomData.usernames - const roomName = names.filter((name, index) => { - return name != SessionStore.user.UserName - })[0] - if (roomName) { + + if (roomData.t == 'd') { + + const username = roomData.usernames.find(e => e != SessionStore.user.UserName) + try { - const firstName = capitalizeTxt(roomName.split('.')[0]) - const lastName = capitalizeTxt(roomName.split('.')[1]) + const firstName = capitalizeTxt(username.split('.')[0]) + const lastName = capitalizeTxt(username.split('.')[1]) + return firstName + ' ' + lastName - } catch (e) { - return roomData['membersExcludeMe'][0].name + } catch (error) { + const username = roomData.usernames.find(e => e != SessionStore.user.UserName) + + const firstName = capitalizeTxt(username.split('.')[0]) + return firstName } - } else if (roomData.name) { - return roomData.name } else { - return 'Sem nome' + if (roomData.t === 'p') { + return 'Loading' + } + else { + return 'Loading' + } } - } else { return roomData.fname } @@ -849,12 +749,10 @@ export class ChatSystemService { async createGroup(name) { const res: any = await this.createPrivateRoom(name, SessionStore.user.UserName, {}); - console.log('room is created', res) if (res?.result?.rid) { try { await this.getAllRooms(); } catch (e) { } - console.log('room is loaded') return res } else { return res diff --git a/src/app/services/chat/rochet-chat-connector.service.ts b/src/app/services/chat/rochet-chat-connector.service.ts index 0130223c9..bd2d2e3c6 100644 --- a/src/app/services/chat/rochet-chat-connector.service.ts +++ b/src/app/services/chat/rochet-chat-connector.service.ts @@ -24,7 +24,7 @@ export class RochetChatConnectorService { connect() { // dont connect if is already connected - if(this.ws.connected == true) { + if (this.ws.connected == true) { return false } @@ -35,29 +35,29 @@ export class RochetChatConnectorService { version: "1", support: ["1"] } - this.ws.send({message, loginRequired: false, requestId: 'connectMessage'}) - this.ws.send({message:{msg:"pong"}, loginRequired: false, requestId: 'connectPong'}) + this.ws.send({ message, loginRequired: false, requestId: 'connectMessage' }) + this.ws.send({ message: { msg: "pong" }, loginRequired: false, requestId: 'connectPong' }) this.ws.registerCallback({ - type:'Onmessage', - key:'ping-pong', - funx:(message: any) => { - if(message.msg == "ping") { - this.ws.send({message:{msg:"pong"}, loginRequired: false}) + type: 'Onmessage', + key: 'ping-pong', + funx: (message: any) => { + if (message.msg == "ping") { + this.ws.send({ message: { msg: "pong" }, loginRequired: false }) } } }) } - wsSend({message, requestId = uuidv4(), loginRequired = true}:send) { - this.ws.send({message:{msg:"pong"}, loginRequired: false}) + wsSend({ message, requestId = uuidv4(), loginRequired = true }: send) { + this.ws.send({ message: { msg: "pong" }, loginRequired: false }) } login() { // dont login if is already login - if(this.isLogin == true) { - return new Promise((resolve, reject)=>{ + if (this.isLogin == true) { + return new Promise((resolve, reject) => { resolve(this.loginResponse) }) } @@ -75,39 +75,41 @@ export class RochetChatConnectorService { } ] } - this.ws.send({message, requestId: 'login', loginRequired: false}) + this.ws.send({ message, requestId: 'login', loginRequired: false }) return new Promise((resolve, reject) => { // - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - // - if(message.id == requestId ) { // same request send + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { // - // - if(message.result) { - if(message.result.token) { - this.isLogin = true - this.loginResponse = message - - setTimeout(()=>{ - this.ws.wsMsgQueue() - }, 10) - - resolve(message) - // - } - } else { - this.isLogin = false + if (message.id == requestId) { // same request send // + // + if (message.result) { + if (message.result.token) { + this.isLogin = true + this.loginResponse = message + + setTimeout(() => { + this.ws.wsMsgQueue() + }, 10) + + resolve(message) + // + } + } else { + this.isLogin = false + // + reject(message) + } + reject(message) + + return true } - - reject(message) - - return true } - }}) + }) }); } @@ -121,18 +123,20 @@ export class RochetChatConnectorService { "msg": "method", "method": "rooms/get", "id": requestId, - "params": [ { "$date": 1480377601 } ] + "params": [{ "$date": 1480377601 }] } - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -142,21 +146,23 @@ export class RochetChatConnectorService { const requestId = uuidv4() const message = { - "msg":"method", - "method":"readMessages", + "msg": "method", + "method": "readMessages", "params": [roomId, []], "id": requestId } - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -176,18 +182,20 @@ export class RochetChatConnectorService { { "limit": 100, "skip": 0 - } ] + }] } - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -198,7 +206,7 @@ export class RochetChatConnectorService { } // send message to room - send({roomId, msg, attachments = null, file = null, localReference = null}) { + send({ roomId, msg, attachments = null, file = null, localReference = null }) { //const requestId = uuidv4() const requestId = uuidv4() @@ -217,15 +225,17 @@ export class RochetChatConnectorService { // - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve({message, requestId}) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve({ message, requestId }) + return true + } } - }}) + }) }); } @@ -240,15 +250,17 @@ export class RochetChatConnectorService { params: [messageObject] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve({message, requestId}) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve({ message, requestId }) + return true + } } - }}) + }) }) } @@ -266,15 +278,17 @@ export class RochetChatConnectorService { ] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -292,15 +306,17 @@ export class RochetChatConnectorService { ] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -315,21 +331,23 @@ export class RochetChatConnectorService { params: [roomId] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - // + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + // - return true + return true + } } - }}) + }) }); } - joinRoom() {} + joinRoom() { } deleteMessage(msgId) { //const requestId = uuidv4(); @@ -338,18 +356,20 @@ export class RochetChatConnectorService { msg: "method", method: "deleteMessage", id: requestId, - params:[{"_id":msgId}] + params: [{ "_id": msgId }] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); - return new Promise ((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message) =>{ - if(message.id == requestId ){ - resolve(message) - return true + return new Promise((resolve, reject) => { + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { + resolve(message) + return true + } } - }}) + }) }); } @@ -366,25 +386,27 @@ export class RochetChatConnectorService { false, customFields, { - "broadcast":false, - "encrypted":false + "broadcast": false, + "encrypted": false } ] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } - sendStreamNotifyRoom(roomId : string, username, event: 'typing', param: any) { + sendStreamNotifyRoom(roomId: string, username, event: 'typing', param: any) { const requestId = uuidv4() @@ -399,21 +421,23 @@ export class RochetChatConnectorService { ] }; - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } - subStreamNotifyRoom(roomId : string , event: 'typing' | 'deleteMessage' | 'readMessage', param: any) { + subStreamNotifyRoom(roomId: string, event: 'typing' | 'deleteMessage' | 'readMessage', param: any) { const requestId = uuidv4() @@ -421,22 +445,24 @@ export class RochetChatConnectorService { msg: "sub", id: requestId, name: "stream-notify-room", - params:[ + params: [ `${roomId}/${event}`, param ] } - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -450,22 +476,24 @@ export class RochetChatConnectorService { msg: "sub", id: requestId, name: "stream-notify-user", - params:[ + params: [ `${SessionStore.user.ChatData.data.userId}/notification`, param ] } - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -473,48 +501,53 @@ export class RochetChatConnectorService { subStreamMessageUser(param?: any) { const requestId = uuidv4() + try { + let message = { + msg: "sub", + id: requestId, + name: "stream-notify-user", + params: [ + `${SessionStore.user.ChatData.data.userId}/message`, + param + ] + } - let message = { - msg: "sub", - id: requestId, - name: "stream-notify-user", - params:[ - `${SessionStore.user.ChatData.data.userId}/message`, - param - ] + + this.ws.send({ message, requestId }) + + return new Promise((resolve, reject) => { + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } + } + }) + }); + } catch (error) { + throw (SessionStore) } - - - this.ws.send({message, requestId}) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true - } - }}) - }); - } receiveStreamNotifyRoom(funx: Function) { this.ws.registerCallback({ - type:'Onmessage', - funx:(message)=> { - if(message.collection == "stream-notify-room" && message.msg == 'changed') { + type: 'Onmessage', + funx: (message) => { + if (message.collection == "stream-notify-room" && message.msg == 'changed') { funx(message) } - }}) + } + }) } - getUserStatus(funx:Function){ + getUserStatus(funx: Function) { this.ws.registerCallback({ - type:'Onmessage', - funx:(message)=>{ - if(message.msg == 'changed' && message.collection == "stream-notify-logged") { + type: 'Onmessage', + funx: (message) => { + if (message.msg == 'changed' && message.collection == "stream-notify-logged") { funx(message) } } @@ -540,16 +573,18 @@ export class RochetChatConnectorService { ] } - this.ws.send({message, requestId: 'loadHistory'}) + this.ws.send({ message, requestId: 'loadHistory' }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - // - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + // + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -562,15 +597,15 @@ export class RochetChatConnectorService { msg: "method", method: `UserPresence:setDefaultStatus`, id: requestId, - params: [ status ] + params: [status] } - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) } - subscribeNotifyRoom(roomId : string) { + subscribeNotifyRoom(roomId: string) { const requestId = uuidv4() @@ -578,37 +613,39 @@ export class RochetChatConnectorService { "msg": "sub", "id": requestId, "name": "stream-notify-room", - "params":[ - `${roomId}/event`, + "params": [ + `${roomId}/event`, false ] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.msg == 'ready' || deepFind(message, 'subs.0') == requestId) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.msg == 'ready' || deepFind(message, 'subs.0') == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } - updateRoomEventss(roomId, collection:string, funx: Function, ) { + updateRoomEventss(roomId, collection: string, funx: Function,) { this.ws.registerCallback({ - type:'Onmessage', - funx:(message)=>{ + type: 'Onmessage', + funx: (message) => { // - if(message.msg =='changed' && message.collection == collection) { - if(message.fields.args[0].rid == roomId) { + if (message.msg == 'changed' && message.collection == collection) { + if (message.fields.args[0].rid == roomId) { funx(message) } - else if(message.fields.eventName ==`${roomId}/deleteMessage`){ + else if (message.fields.eventName == `${roomId}/deleteMessage`) { funx(message) } } @@ -616,31 +653,33 @@ export class RochetChatConnectorService { }) } - streamRoomMessages(roomId : string) { + streamRoomMessages(roomId: string) { - const requestId = "streamRoomMessages"+uuidv4() + const requestId = "streamRoomMessages" + uuidv4() const message = { "msg": "sub", "id": requestId, "name": "stream-room-messages", - "params":[ + "params": [ `${roomId}`, - false + false ] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message) => { + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { - if(message.id == requestId || message?.subs?.[0] == requestId) { // same request send - resolve(message) - return true + if (message.id == requestId || message?.subs?.[0] == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } @@ -652,25 +691,27 @@ export class RochetChatConnectorService { "msg": "sub", "id": requestId, "name": "stream-notify-logged", - "params":[ + "params": [ "user-status", - false + false ] } - this.ws.send({message, requestId}); + this.ws.send({ message, requestId }); return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } - streamNotifyRoom(roomId : string) { + streamNotifyRoom(roomId: string) { const requestId = uuidv4() @@ -685,20 +726,22 @@ export class RochetChatConnectorService { ] }; - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } - streamNotifyRoomDeleteMessage(roomId:string) { + streamNotifyRoomDeleteMessage(roomId: string) { const requestId = uuidv4() @@ -712,34 +755,36 @@ export class RochetChatConnectorService { ] }; - this.ws.send({message, requestId}) + this.ws.send({ message, requestId }) return new Promise((resolve, reject) => { - this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId ) { // same request send - resolve(message) - return true + this.ws.registerCallback({ + type: 'Onmessage', funx: (message) => { + if (message.id == requestId) { // same request send + resolve(message) + return true + } } - }}) + }) }); } - registerCallback(data:wsCallbacksParams) { + registerCallback(data: wsCallbacksParams) { return this.ws.registerCallback(data) } // socket class ================================================================== private socket!: WebSocket; - private wsMsgQueue : {[key: string]: msgQueue} = {} - private wsCallbacks: {[key: string]: wsCallbacksParams} = {} + private wsMsgQueue: { [key: string]: msgQueue } = {} + private wsCallbacks: { [key: string]: wsCallbacksParams } = {} private wsReconnect = 0 private n = 0 - ws = { + ws = { connected: false, - registerCallback:(params: wsCallbacksParams) => { + registerCallback: (params: wsCallbacksParams) => { let id = params.requestId || params.key || uuidv4() // @@ -747,7 +792,7 @@ export class RochetChatConnectorService { this.n++ return id }, - connect:()=> { + connect: () => { this.socket = new WebSocket(environment.apiWsChatUrl); // bind function this.socket.onopen = this.ws.onopen; @@ -756,24 +801,24 @@ export class RochetChatConnectorService { this.socket.onerror = this.ws.onerror; }, - onopen: async ()=> { + onopen: async () => { this.ws.connected = true this.backgroundservice.online(); - setTimeout(()=>{ + setTimeout(() => { this.ws.wsMsgQueue() }, 10) console.log('rec conect') - if(this.wsReconnect >= 1) { + if (this.wsReconnect >= 1) { for (const [key, value] of Object.entries(this.wsCallbacks)) { - if(value.type== 'reConnect') { + if (value.type == 'reConnect') { const dontRepeat = await value.funx() - if(dontRepeat) { + if (dontRepeat) { this.n-- delete this.wsCallbacks[key] } @@ -785,28 +830,28 @@ export class RochetChatConnectorService { this.wsReconnect++; }, - wsMsgQueue:()=> { + wsMsgQueue: () => { for (const [key, item] of Object.entries(this.wsMsgQueue)) { - if(item.loginRequired == true && this.isLogin == true) { + if (item.loginRequired == true && this.isLogin == true) { // this.ws.send(item); delete this.wsMsgQueue[key] - } else if(item.loginRequired == false) { + } else if (item.loginRequired == false) { // this.ws.send(item); delete this.wsMsgQueue[key] } } }, - send: ({message, requestId = uuidv4(), loginRequired = true}:send) => { + send: ({ message, requestId = uuidv4(), loginRequired = true }: send) => { if (this.ws.connected == false || loginRequired == true && this.isLogin == false) { // save data to send when back online // // - this.wsMsgQueue[requestId] = {message, requestId, loginRequired} + this.wsMsgQueue[requestId] = { message, requestId, loginRequired } } else { let messageStr = JSON.stringify(message) this.socket.send(messageStr) @@ -814,17 +859,17 @@ export class RochetChatConnectorService { return requestId }, - onmessage: async (event: any)=> { + onmessage: async (event: any) => { this.backgroundservice.online(); const data = JSON.parse(event.data) for (const [key, value] of Object.entries(this.wsCallbacks)) { - if(value.type== 'Onmessage') { + if (value.type == 'Onmessage') { const dontRepeat = await value.funx(data) - if(dontRepeat) { + if (dontRepeat) { delete this.wsCallbacks[key] this.n-- } @@ -835,7 +880,7 @@ export class RochetChatConnectorService { }, - onclose: async (event: any)=> { + onclose: async (event: any) => { this.ws.connected = false this.isLogin = false @@ -844,10 +889,10 @@ export class RochetChatConnectorService { this.login() for (const [key, value] of Object.entries(this.wsCallbacks)) { - if(value.type == 'Offline') { + if (value.type == 'Offline') { const dontRepeat = await value.funx() - if(dontRepeat) { + if (dontRepeat) { delete this.wsCallbacks[key] this.n-- } @@ -859,16 +904,16 @@ export class RochetChatConnectorService { }, - onerror: (event: any) => { + onerror: (event: any) => { }, - disconnect:() => { + disconnect: () => { - if(this.socket) { - this.socket.onopen = (event: any) => {} - this.socket.onmessage = (event: any) => {} - this.socket.onclose = (event: any) => {} - this.socket.onerror = (event: any) => {} + if (this.socket) { + this.socket.onopen = (event: any) => { } + this.socket.onmessage = (event: any) => { } + this.socket.onclose = (event: any) => { } + this.socket.onerror = (event: any) => { } this.socket.close() } } diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index 8cff5958d..5a2aa305c 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -20,7 +20,7 @@ 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'; +import { ConnectionStatus, NetworkServiceService } from 'src/app/services/network-service.service'; import { ChatSystemService } from './chat-system.service'; import { ViewedMessageService } from './viewed-message.service' import * as FIFOProcessQueue from 'fifo-process-queue'; @@ -57,7 +57,7 @@ export class RoomService { u sessionStore = SessionStore countDownTime = '' - chatOpen = false + chatOpen = false messageUnread = false status = { @@ -78,12 +78,12 @@ export class RoomService { * @description get user list from ws-chat-methods.service * @returns chatUser[] */ - getAllUsers = (): chatUser[] => { + getAllUsers = (): chatUser[] => { return [] } - sortRoomList = () => {} - chatServiceDeleteRoom = (roomId) => {} + sortRoomList = () => { } + chatServiceDeleteRoom = (roomId) => { } constructor( public RochetChatConnectorService: RochetChatConnectorService, @@ -130,22 +130,22 @@ export class RoomService { } - /** - * @description convert rocketchat statues num to readable string - * @param text - * @returns - */ + /** + * @description convert rocketchat statues num to readable string + * @param text + * @returns + */ statusNumberToText(text) { - if(text == '0') { + if (text == '0') { return "offline" } - else if(text == '1') { + else if (text == '1') { return "online" } - else if(text == '2') { + else if (text == '2') { return "away" } - else if(text == '3') { + else if (text == '3') { return "busy" } } @@ -162,7 +162,8 @@ export class RoomService { } } - setData({membersExcludeMe, members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService,this.notificationService), _updatedAt }) { + setDataOnce = false + setData({ membersExcludeMe, members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService, this.notificationService), _updatedAt }) { this.customFields = customFields this.id = id this.name = name @@ -170,16 +171,18 @@ export class RoomService { this.lastMessage = lastMessage this._updatedAt = _updatedAt this.u = u - this.members = members - this.membersExcludeMe = membersExcludeMe - this.calDateDuration(); - if(this.customFields?.countDownDate) { + if (this.customFields?.countDownDate) { this.countDownDate(this.customFields.countDownDate); } + if (this.setDataOnce == false) { + this.setDataOnce = true + this.updateContacts() + } + } updateInfo() { @@ -189,11 +192,11 @@ export class RoomService { get online() { - if(!this.isGroup) { - for(let user of this.ChatSystemService.users) { + if (!this.isGroup) { + for (let user of this.ChatSystemService.users) { for (const members of this.membersExcludeMe) { - if(members._id == user._id) { + if (members._id == user._id) { return user.status } } @@ -206,14 +209,14 @@ export class RoomService { countDownDate(date) { let difference = new Date(date).getTime() - new Date().getTime(); - let c_day = Math.floor(difference/(1000*60*60*24)); - let c_hours = Math.floor((difference % (1000*60*60*24)) / (1000*60*60)); - let c_minutes = Math.floor((difference % (1000*60*60)) / (1000*60)); - let c_seconds = Math.floor((difference % (1000*60)) / 1000); + let c_day = Math.floor(difference / (1000 * 60 * 60 * 24)); + let c_hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); + let c_minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)); + let c_seconds = Math.floor((difference % (1000 * 60)) / 1000); - this.countDownTime = this.addZero(c_day) + " : " + this.addZero(c_hours) + " : " + this.addZero(c_minutes) + " : " + this.addZero(c_seconds) ; + this.countDownTime = this.addZero(c_day) + " : " + this.addZero(c_hours) + " : " + this.addZero(c_minutes) + " : " + this.addZero(c_seconds); - if(difference < 0) { + if (difference < 0) { this.deleteRoom(); @@ -237,15 +240,15 @@ export class RoomService { // this.chatService.getRoomInfo(this.id).subscribe( room =>{}); - if(this.t === 'p') { - this.chatService.deleteGroup(body).subscribe(res=>{ + if (this.t === 'p') { + this.chatService.deleteGroup(body).subscribe(res => { this.ChatSystemService.deleteRoom(this.id); this.ChatSystemService.getAllRooms(); this.chatServiceDeleteRoom(this.id); }); } else { - this.chatService.deleteChannel(body).subscribe(res=>{ + this.chatService.deleteChannel(body).subscribe(res => { this.ChatSystemService.deleteRoom(this.id); this.ChatSystemService.getAllRooms(); this.chatServiceDeleteRoom(this.id); @@ -267,7 +270,7 @@ export class RoomService { this.RochetChatConnectorService.updateRoomEventss( this.id, "stream-room-messages", - async (IncomingChatMessage:IncomingChatMessage) => { + async (IncomingChatMessage: IncomingChatMessage) => { this.appendReceiveMessage.push(IncomingChatMessage) @@ -276,29 +279,29 @@ export class RoomService { this.RochetChatConnectorService.receiveStreamNotifyRoom((message) => { - if(message.fields.eventName == this.id+'/'+'typing') { + if (message.fields.eventName == this.id + '/' + 'typing') { const args = message.fields.args if (typeof args[1] != 'object') { this.userThatIsTyping = this.usernameToDisplayName(args[0]) - this.isTyping = args[1] + this.isTyping = args[1] this.otherUserType = args[1] const user = args[0] - if(SessionStore.user.UserName != user) { + if (SessionStore.user.UserName != user) { this.readAllMessage() } - } else if(args[0]?.method == 'viewMessage' || args[1]?.method == 'viewMessage') { + } else if (args[0]?.method == 'viewMessage' || args[1]?.method == 'viewMessage') { const user = args[0] - if(SessionStore.user.UserName != user) { + if (SessionStore.user.UserName != user) { this.readAllMessage() } - } else if(args[0]?.method == 'deleteMessage' || args[1]?.method == 'deleteMessage') { + } else if (args[0]?.method == 'deleteMessage' || args[1]?.method == 'deleteMessage') { this.deleteMessage(args[1]?.method?._id) @@ -306,25 +309,25 @@ export class RoomService { } - } else if (message.fields.eventName == this.id+'/'+'deleteMessage') {} + } else if (message.fields.eventName == this.id + '/' + 'deleteMessage') { } }) } - appendReceiveMessage = FIFOProcessQueue(async (IncomingChatMessage:IncomingChatMessage, done) => { + appendReceiveMessage = FIFOProcessQueue(async (IncomingChatMessage: IncomingChatMessage, done) => { let IncomingChatMessageArgs = IncomingChatMessage.fields.args[0] - let ChatMessage : ChatMessageInterface = this.fix_updatedAt(IncomingChatMessageArgs) + let ChatMessage: ChatMessageInterface = this.fix_updatedAt(IncomingChatMessageArgs) let found = this.findMessageBy_id(ChatMessage._id) || - this.findMessageBy_localReference(ChatMessage?.localReference) + this.findMessageBy_localReference(ChatMessage?.localReference) // || await this.findMessageInDBByData({_id:ChatMessage._id, localReference:ChatMessage.localReference }) - if(!found) { + if (!found) { ChatMessage.origin = 'stream' - const message = await this.prepareCreate({message: ChatMessage, save: false}); + const message = await this.prepareCreate({ message: ChatMessage, save: false }); this.registerSendMessage(message) message.from = 'stream' @@ -337,14 +340,14 @@ export class RoomService { 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) { + if (this.hasLoadHistory == true) { this.messages.push(message) await message.addMessageDB() } else { @@ -360,7 +363,7 @@ export class RoomService { } - if(ChatMessage?.t == "au" || ChatMessage?.t == "ru" || ChatMessage?.t == "ul") { + if (ChatMessage?.t == "au" || ChatMessage?.t == "ru" || ChatMessage?.t == "ul") { this.updateContacts() } else if (ChatMessage?.t == "r") { this.name = ChatMessage.msg @@ -374,8 +377,8 @@ export class RoomService { getUsersByStatus(status: 'offline' | 'online') { return this.getAllUsers().filter((user => { - for(const member of this.membersExcludeMe) { - if(user._id == member._id && user.status == status) { + for (const member of this.membersExcludeMe) { + if (user._id == member._id && user.status == status) { return true } } @@ -385,8 +388,8 @@ export class RoomService { getRoomMembersIds(): string[] { try { - return this.membersExcludeMe.map((user)=> user._id) - } catch(error) { + return this.membersExcludeMe.map((user) => user._id) + } catch (error) { return [] } @@ -399,10 +402,10 @@ export class RoomService { const AllMemberThatIsNotOffline = [] - for(let user of allChatUsers) { - if(membersIds.includes(user._id)) { + for (let user of allChatUsers) { + if (membersIds.includes(user._id)) { - if(user.status != 'offline') { + if (user.status != 'offline') { AllMemberThatIsNotOffline.push(user._id) } } @@ -418,10 +421,10 @@ export class RoomService { const AllMemberThatIsNotOffline = [] - for(let user of allChatUsers) { - if(membersIds.includes(user._id)) { + for (let user of allChatUsers) { + if (membersIds.includes(user._id)) { - if(user.status == 'offline') { + if (user.status == 'offline') { AllMemberThatIsNotOffline.push(user._id) } } @@ -433,18 +436,18 @@ export class RoomService { async deleteMessageToReceive(userId) { - const allDeleteMessages = await DeleteMessageModel.filter({rid: this.id}).execute() + const allDeleteMessages = await DeleteMessageModel.filter({ rid: this.id }).execute() - for(let message_ of allDeleteMessages) { + for (let message_ of allDeleteMessages) { - if(message_.needToReceiveBy.includes(userId)) { + if (message_.needToReceiveBy.includes(userId)) { - message_.needToReceiveBy = message_.needToReceiveBy.filter((e)=> e != userId) - this.sendFalseTypingReadMessage('deleteMessage',{_id:message_.messageId}) + message_.needToReceiveBy = message_.needToReceiveBy.filter((e) => e != userId) + this.sendFalseTypingReadMessage('deleteMessage', { _id: message_.messageId }) - if(message_.needToReceiveBy.length == 0) { + if (message_.needToReceiveBy.length == 0) { - const deleteMessage = await DeleteMessageModel.get({messageId: message_.messageId}) + const deleteMessage = await DeleteMessageModel.get({ messageId: message_.messageId }) await deleteMessage.delete() } else { @@ -467,13 +470,13 @@ export class RoomService { const message = this.messages.find((e) => e._id == DeletedMessageId) - if(message) { - if(message.delate == false) { + if (message) { + if (message.delate == false) { this.deleteMessage(DeletedMessageId) } } else { - const message = await MessageModel.get({_id: DeletedMessageId}) - if(message) { + const message = await MessageModel.get({ _id: DeletedMessageId }) + if (message) { (message as MessageModel).delete() DeleteMessageModel.create({ @@ -496,13 +499,13 @@ export class RoomService { * @description delete message in the view * @param id message ID */ - async deleteMessage(_id) { + async deleteMessage(_id) { const id = _id - for (let i =0; i <= this.messages.length; i++) { + for (let i = 0; i <= this.messages.length; i++) { - if(this.messages[i]?._id == id ) { + if (this.messages[i]?._id == id) { if (SessionStore.user.UserName == this.messages[i]?.u?.username) { @@ -523,8 +526,8 @@ export class RoomService { //Get previous last message from room const previousLastMessage = this.messages.slice(-1)[0]; - if(previousLastMessage.dateLabel == false) { - if(previousLastMessage) { + if (previousLastMessage.dateLabel == false) { + if (previousLastMessage) { this.lastMessage = previousLastMessage; this.calDateDuration(previousLastMessage._updatedAt) this.sortRoomList() @@ -532,7 +535,7 @@ export class RoomService { } else { const previousLastMessage = this.messages.slice(-2)[0]; - if(previousLastMessage) { + if (previousLastMessage) { this.lastMessage = previousLastMessage; this.calDateDuration(previousLastMessage._updatedAt) this.sortRoomList() @@ -552,17 +555,17 @@ export class RoomService { } - /** - * @description delete message in the view - * @param id message ID - */ + /** + * @description delete message in the view + * @param id message ID + */ async deleteMessageFromArray(_id) { const id = _id - for (let i =0; i <= this.messages.length; i++) { + for (let i = 0; i <= this.messages.length; i++) { - if(this.messages[i]?._id == id ) { + if (this.messages[i]?._id == id) { this.messages.splice(i, 1) @@ -578,7 +581,7 @@ export class RoomService { deleteAll() { this.messages.forEach((message) => { - if(message?._id) { + if (message?._id) { this.sendDeleteRequest(message._id) } }) @@ -588,19 +591,19 @@ export class RoomService { const deleteMessage = await DeleteMessageModel.all(); - const toSend = deleteMessage.filter((DeleteMessage:string[])=> ! DeleteMessage.includes(userId)) + const toSend = deleteMessage.filter((DeleteMessage: string[]) => !DeleteMessage.includes(userId)) } async sendDeleteRequest(msgId) { - const message = this.messages.find((e)=>e._id == msgId) + const message = this.messages.find((e) => e._id == msgId) await message.delateStatusFalse() - if(this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) { + if (this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) { - this.RochetChatConnectorService.deleteMessage(msgId).then(async() => { + this.RochetChatConnectorService.deleteMessage(msgId).then(async () => { message.delateRequest = true await message.saveChanges(); this.deleteMessage(msgId); @@ -609,7 +612,7 @@ export class RoomService { } else { this.RochetChatConnectorService.registerCallback({ type: 'reConnect', - funx: async ()=> { + funx: async () => { this.sendDeleteRequest(msgId) return true @@ -623,11 +626,11 @@ export class RoomService { /** * @description sen text message */ - async send({file = null, attachments = null, temporaryData = {}, attachmentsModelData = {}}) { + async send({ file = null, attachments = null, temporaryData = {}, attachmentsModelData = {} }) { - this.message = this.message.replace(/(\n$)/,'') + this.message = this.message.replace(/(\n$)/, '') - if(file && this.message) { + if (file && this.message) { this.send({}) } @@ -647,14 +650,14 @@ export class RoomService { //console.log('offlineChatMessage', offlineChatMessage) - this.message= '' + this.message = '' - this.hojeLabel({...offlineChatMessage}) + this.hojeLabel({ ...offlineChatMessage }) - const message: MessageService = await this.prepareCreate({message:offlineChatMessage, save: environment.chatOffline}) + const message: MessageService = await this.prepareCreate({ message: offlineChatMessage, save: environment.chatOffline }) this.registerSendMessage(message) - if(this.hasLoadHistory == true) { + if (this.hasLoadHistory == true) { await message.addMessageDB() } @@ -686,27 +689,27 @@ export class RoomService { localReferenceExist(message: MessageService) { - for( const localReference of this.messagesLocalReference) { - if(localReference == message?.localReference) { + for (const localReference of this.messagesLocalReference) { + if (localReference == message?.localReference) { return true } } return false } - sendTyping(text:string = this.message) { + sendTyping(text: string = this.message) { - if(this.lastMessageTxt == text) { return false } + if (this.lastMessageTxt == text) { return false } this.lastTimeType = new Date().getTime() const lastIsTyping = this.isTyping - if(text.length >= 1) { + if (text.length >= 1) { this.isTyping = true } else { this.isTyping = false } - if(lastIsTyping != this.isTyping) { + if (lastIsTyping != this.isTyping) { this.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', this.isTyping).catch((error) => console.error(error)); } @@ -714,8 +717,8 @@ export class RoomService { this.typingWatch() } - sendFalseTypingReadMessage(method,param: object) { - this.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', {method:method, params: param} as falseTypingMethod).catch((error) => console.error(error)) + sendFalseTypingReadMessage(method, param: object) { + this.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', { method: method, params: param } as falseTypingMethod).catch((error) => console.error(error)) this.setTypingOff() } @@ -723,9 +726,9 @@ export class RoomService { setTimeout(() => { const now = new Date().getTime() - if((now - this.lastTimeType) >= 2888) { + if ((now - this.lastTimeType) >= 2888) { - if(this.isTyping == true) { + if (this.isTyping == true) { this.isTyping = false this.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', this.isTyping).catch((error) => console.error(error)) } @@ -776,8 +779,8 @@ export class RoomService { sortArrayISODate(messages: any): any[] { - return messages.sort((a,b) => - new Date(b._updatedAt ).getTime() + return messages.sort((a, b) => + new Date(b._updatedAt).getTime() - new Date(a._updatedAt).getTime()) } @@ -789,16 +792,16 @@ export class RoomService { goshPush(ChatMessage) { let currentDateMessage = new Date(ChatMessage._updatedAt).toLocaleDateString() - if(currentDateMessage) { - if(!this.labelDates.find( e => e == currentDateMessage)) { + if (currentDateMessage) { + if (!this.labelDates.find(e => e == currentDateMessage)) { this.labelDates.push(currentDateMessage) - const newMessage = this.fix_updatedAt({...ChatMessage}) + const newMessage = this.fix_updatedAt({ ...ChatMessage }) newMessage.msg = currentDateMessage const cloneMessage = new MessageServiceDateLabel() cloneMessage.ChatSystemService = this.ChatSystemService - cloneMessage.setData({...newMessage} as any) + cloneMessage.setData({ ...newMessage } as any) // cloneMessage._id = "" cloneMessage._updatedAt = "" @@ -809,7 +812,7 @@ export class RoomService { cloneMessage.file = undefined cloneMessage.attachments = undefined - if(new Date().toLocaleDateString() == currentDateMessage) { + if (new Date().toLocaleDateString() == currentDateMessage) { cloneMessage.msg = "hoje" } else { @@ -827,18 +830,18 @@ export class RoomService { let currentDateMessageToDelete = new Date(MessageService._updatedAt).toLocaleDateString() - for (let i =0; i <= this.messages.length; i++) { + for (let i = 0; i <= this.messages.length; i++) { let currentDateMessage = new Date(this.messages[i]._updatedAt).toLocaleDateString() - if(currentDateMessageToDelete == currentDateMessage) { + if (currentDateMessageToDelete == currentDateMessage) { return } } - for (let i =0; i <= this.messages.length; i++) { - if(this.messages[i].dateLabel) { - if(this.messages[i].msg == currentDateMessageToDelete) { + for (let i = 0; i <= this.messages.length; i++) { + if (this.messages[i].dateLabel) { + if (this.messages[i].msg == currentDateMessageToDelete) { this.messages.splice(i, 1) } } @@ -849,14 +852,14 @@ export class RoomService { hojeLabel(offlineChatMessage: any) { let currentDateMessage = new Date().toLocaleDateString() - if(!this.labelDates.find( e => e == currentDateMessage)) { + if (!this.labelDates.find(e => e == currentDateMessage)) { this.labelDates.push(currentDateMessage) const cloneMessage = new MessageServiceDateLabel() cloneMessage.ChatSystemService = this.ChatSystemService - cloneMessage.setData({...offlineChatMessage} as any) + cloneMessage.setData({ ...offlineChatMessage } as any) cloneMessage.msg = "hoje" cloneMessage._id = "" @@ -872,12 +875,12 @@ export class RoomService { } async restoreMessageFromDB() { - if(environment.chatOffline && this.restoreOnce == false) { + if (environment.chatOffline && this.restoreOnce == false) { this.restoreOnce = true - const messages = this.sortArrayISODate(await MessageModel.filter({rid:this.id}).execute()).reverse() + const messages = this.sortArrayISODate(await MessageModel.filter({ rid: this.id }).execute()).reverse() - for (let ChatMessage of messages) { + for (let ChatMessage of messages) { this.goshPush(ChatMessage) @@ -889,9 +892,9 @@ export class RoomService { wewMessage.loadHistory = this.hasLoadHistory wewMessage.messageModelInstance = ChatMessage - if(wewMessage.offline == false) { + if (wewMessage.offline == false) { - const message = await this.prepareCreate({message:ChatMessage}) + const message = await this.prepareCreate({ message: ChatMessage }) message.from = 'Offline' @@ -901,7 +904,7 @@ export class RoomService { } else { - const offlineMessage = await this.prepareCreate({message:ChatMessage}) + const offlineMessage = await this.prepareCreate({ message: ChatMessage }) offlineMessage.from = 'Offline' offlineMessage.loadHistory = this.hasLoadHistory @@ -912,12 +915,12 @@ export class RoomService { } - if(wewMessage.delate && !wewMessage.offline && !wewMessage.delateRequest) { + if (wewMessage.delate && !wewMessage.offline && !wewMessage.delateRequest) { this.sendDeleteRequest(wewMessage._id) } } - if(!this.lastMessage) { + if (!this.lastMessage) { this.lastMessage = messages.pop(); } @@ -931,9 +934,9 @@ export class RoomService { // runs onces only loadHistoryCount = 0 localMessages = [] - async loadHistory({limit = 1000, forceUpdate = false }) { + async loadHistory({ limit = 1000, forceUpdate = false }) { - if(forceUpdate == false) { + if (forceUpdate == false) { if (this.hasLoadHistory) { return false } @@ -944,18 +947,18 @@ export class RoomService { await this.restoreMessageFromDB() const chatHistory: chatHistory = await this.RochetChatConnectorService.loadHistory(this.id, limit) - this.localMessages = this.messages.map( e => e._id) + this.localMessages = this.messages.map(e => e._id) - if(chatHistory?.result?.messages) { + if (Array.isArray(chatHistory?.result?.messages)) { const users = this.getUsersByStatus('online') - for(let message of chatHistory.result.messages.reverse()) { + for (let message of chatHistory.result.messages.reverse()) { message.origin = 'history' message.from = 'History' - const messagesToSave = await this.prepareMessageCreateIfNotExist({message: message}); - if(messagesToSave != null) { + const messagesToSave = await this.prepareMessageCreateIfNotExist({ message: message }); + if (messagesToSave != null) { messagesToSave.received = users.map((user) => user._id) messagesToSave.addMessageDB() @@ -964,13 +967,13 @@ export class RoomService { } - for( const message of this.messagesBeforeOfflineAPI) { - const messagesToSave = await this.prepareMessageCreateIfNotExist({message: message}); - if(messagesToSave != null) { + for (const message of this.messagesBeforeOfflineAPI) { + const messagesToSave = await this.prepareMessageCreateIfNotExist({ message: message }); + if (messagesToSave != null) { messagesToSave.received = users.map((user) => user._id) - this.addMessageDB.push(messagesToSave) + this.addMessageDB.push(messagesToSave) } } this.messagesBeforeOfflineAPI = [] @@ -983,9 +986,9 @@ export class RoomService { this.DoneLoadingHistory = true - if(chatHistory?.result?.messages) { + if (chatHistory?.result?.messages) { - if(!this.lastMessage) { + if (!this.lastMessage) { this.lastMessage = chatHistory?.result?.messages.pop() as any } } @@ -996,11 +999,11 @@ export class RoomService { deletedMessages(chatHistory: chatHistory) { - const messagesToDelete = this.localMessages.filter( id => { - const found = chatHistory.result.messages.find( e => { + const messagesToDelete = this.localMessages.filter(id => { + const found = chatHistory.result.messages.find(e => { return e._id == id }) - if(!found) { + if (!found) { return true } @@ -1009,13 +1012,13 @@ export class RoomService { for (const id of messagesToDelete) { - if(id != '') { + if (id != '') { this.deleteMessage(id) } } } - addMessageDB = FIFOProcessQueue(async ({messagesToSave}, callback) => { + addMessageDB = FIFOProcessQueue(async ({ messagesToSave }, callback) => { await messagesToSave.addMessageDB() callback() @@ -1029,7 +1032,7 @@ export class RoomService { - async ChatMessageIsPresentInTheView(ChatMessage:ChatMessageInterface) { + async ChatMessageIsPresentInTheView(ChatMessage: ChatMessageInterface) { let foundIndex; const found = this.messages.find((MessageService, index) => { @@ -1042,7 +1045,7 @@ export class RoomService { }) if (foundIndex) { - return { found, foundIndex} + return { found, foundIndex } } else { return false } @@ -1051,14 +1054,14 @@ export class RoomService { - async prepareCreate({message, save = true}): Promise { + async prepareCreate({ message, save = true }): Promise { message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService,this.notificationService) + const wewMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService, this.notificationService) wewMessage.setData(message) wewMessage.loadHistory = this.hasLoadHistory - if(save) { + if (save) { this.messages.push(wewMessage) } @@ -1068,7 +1071,7 @@ export class RoomService { simplePrepareMessage(message) { message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService,this.notificationService) + const wewMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService, this.notificationService) wewMessage.setData(message) wewMessage.loadHistory = this.hasLoadHistory @@ -1076,9 +1079,9 @@ export class RoomService { } - private findMessageBy_id (id) { - for( let m of this.messages) { - if(m?._id == id) { + private findMessageBy_id(id) { + for (let m of this.messages) { + if (m?._id == id) { return true } } @@ -1086,9 +1089,9 @@ export class RoomService { return false } - private findMessageBy_localReference (localReference) { - for( let m of this.messages) { - if(m?.localReference == localReference) { + private findMessageBy_localReference(localReference) { + for (let m of this.messages) { + if (m?.localReference == localReference) { return true } } @@ -1096,27 +1099,27 @@ export class RoomService { return false } - private async findMessageInDBByLocalReference({localReference}) { - const a = await MessageModel.get({localReference: localReference}) + private async findMessageInDBByLocalReference({ localReference }) { + const a = await MessageModel.get({ localReference: localReference }) return typeof a.id == 'number' } - private async findMessageInDBByLocalId({_id}) { - const a = await MessageModel.get({_id: _id}) + private async findMessageInDBByLocalId({ _id }) { + const a = await MessageModel.get({ _id: _id }) return typeof a.id == 'number' } - private async findMessageInDBByData({localReference, _id}) { + private async findMessageInDBByData({ localReference, _id }) { - const a = await MessageModel.filter({localReference: localReference}).execute() - if(a.length >= 1) { + const a = await MessageModel.filter({ localReference: localReference }).execute() + if (a.length >= 1) { return true } - const c = await MessageModel.filter({_id: _id}).execute() - if(c.length >= 1) { + const c = await MessageModel.filter({ _id: _id }).execute() + if (c.length >= 1) { return true } @@ -1125,7 +1128,7 @@ export class RoomService { return false } - async prepareMessageCreateIfNotExist({message}) { + async prepareMessageCreateIfNotExist({ message }) { message = this.fix_updatedAt(message) let found = await this.findMessageBy_id(message._id) || await this.findMessageBy_localReference(message.localReference) @@ -1135,7 +1138,7 @@ export class RoomService { const wewMessage = this.simplePrepareMessage(message) this.goshPush(wewMessage) this.messages.push(wewMessage) - return wewMessage + return wewMessage } else { return null } @@ -1149,8 +1152,8 @@ export class RoomService { private fix_updatedAt(message): ChatMessageInterface { if (message?.result) { message.result._updatedAt = message.result._updatedAt['$date'] - } else if(message?._updatedAt) { - if(message._updatedAt.hasOwnProperty('$date')) { + } else if (message?._updatedAt) { + if (message._updatedAt.hasOwnProperty('$date')) { message._updatedAt = message._updatedAt['$date'] } } @@ -1161,23 +1164,23 @@ export class RoomService { try { const firstName = capitalizeTxt(username.split('.')[0]) - const lastName = capitalizeTxt(username.split('.')[1]) + const lastName = capitalizeTxt(username.split('.')[1]) return firstName + ' ' + lastName - } catch(error) { + } catch (error) { return username } } sendReadMessage() { - this.RochetChatConnectorService.readMessage(this.id).catch((error) =>{ + this.RochetChatConnectorService.readMessage(this.id).catch((error) => { console.error(error) }) this.sendFalseTypingReadMessage('viewMessage', {}) this.messageUnread = false } - async addContacts(userId:any) { + async addContacts(userId: any) { let body = { "roomId": this.id, @@ -1194,7 +1197,7 @@ export class RoomService { let res let error = false - if(this.t == 'd') { + if (this.t == 'd') { try { res = await this.chatService.getMembers(this.id).toPromise(); @@ -1203,7 +1206,7 @@ export class RoomService { error = true } - if(error) { + if (error) { res = await this.chatService.getMembers(this.id).toPromise(); } @@ -1217,11 +1220,14 @@ export class RoomService { error = true } - if(error) { + if (error) { res = await this.chatService.getGroupMembers(this.id).toPromise() } + setTimeout(() => { + console.log("getGroupMembers", this.membersExcludeMe) + }, 500) } else { @@ -1234,10 +1240,13 @@ export class RoomService { error = true } - if(error) { + if (error) { res = await this.chatService.getChannelMembers(this.id).toPromise() } + setTimeout(() => { + console.log("getChannelMembers", this.membersExcludeMe) + }, 500) } } diff --git a/src/app/services/notifications.service.ts b/src/app/services/notifications.service.ts index 1bd0e3806..0fc9bedd1 100644 --- a/src/app/services/notifications.service.ts +++ b/src/app/services/notifications.service.ts @@ -90,7 +90,7 @@ export class NotificationsService { } } - private getAndpostToken(username) { + private getAndpostToken(username) { const geturl = environment.apiURL + 'notifications/token'; if (this.platform.is('mobile')) { @@ -367,13 +367,19 @@ export class NotificationsService { let navigationExtras: NavigationExtras = { queryParams: { "roomId": notification.notification.data.IdObject, } }; - this.zone.run(() => this.router.navigate(['/home/chat'])); + if (window.location.search.includes("roomId")) { + this.zone.run(() => this.router.navigate(['/home/chat'])); + } setTimeout(() => { this.zone.run(() => this.router.navigate(['/home/chat'], navigationExtras)); }, 200); } + + // (() => { + // this.zone.run(() => this.NotificationHolderService.PhoneClickNotification(notification)); + // })() } } diff --git a/src/app/store/notification-holder.service.ts b/src/app/store/notification-holder.service.ts index 675729736..c37aa9906 100644 --- a/src/app/store/notification-holder.service.ts +++ b/src/app/store/notification-holder.service.ts @@ -1,6 +1,7 @@ import { Injectable, NgZone } from '@angular/core'; import { StorageService } from '../services/storage.service'; import { v4 as uuidv4 } from 'uuid' +import { SHA1 } from 'crypto-js'; @Injectable({ providedIn: 'root' }) @@ -40,17 +41,13 @@ export class NotificationHolderService { this.storageService.store("Notifications", this._notificationList) } - addNotification(notification) { - + notificationObject(notification) { const element = notification - const i = this._notificationList.length + 1 - let notificationObject; if (element.notification) { notificationObject = { - id: notification?.id || uuidv4(), - index: i, + id: notification?.id, title: element.notification.title, Service: element.data.Service, Object: element.data.Object, @@ -68,8 +65,7 @@ export class NotificationHolderService { } else if (element.data) { notificationObject = { - id: notification?.id || uuidv4(), - index: i, + id: notification?.id, title: element.title, Service: element.data.Service, Object: element.data.Object, @@ -88,25 +84,38 @@ export class NotificationHolderService { } else { { notificationObject = { - id: notification?.id || uuidv4(), - FolderId: element.FolderId, - IdObject: element.IdObject, - Location: element.Location, - Object: element.Object, - Role: element.Role, - Service: element.Service, - Status: element.Status, - TypeAgenda: element.TypeAgenda, - body: element.body, - dateEnd: element.dateEnd, - dateInit: element.dateInit, - index: element.index, + id: notification?.id, title: element.title, + Service: element.Service, + Object: element.Object, + IdObject: element.IdObject, + FolderId: element.FolderId, + body: element.body, + dateInit: element.dateInit, + dateEnd: element.dateEnd, + Location: element.Location, + TypeAgenda: element.TypeAgenda, + Role: element.Role, + Status: element.Status, read: false, } } } + notificationObject.hashCode = (SHA1(notification)).toString() + + return notificationObject + } + + + + addNotification(notification) { + + let notificationObject = this.notificationObject(notification) + + //alert("add notification") + //alert(JSON.stringify(notificationObject)) + if (!this.notificationExist(notificationObject)) { this._notificationList.push(notificationObject) @@ -115,14 +124,11 @@ export class NotificationHolderService { this.save() }) - } else { console.log('duplicate', notification, this._notificationList) } } - - notificationExist(notificationObject) { const notification = this._notificationList.find(item => { return item.id === notificationObject.id; @@ -166,4 +172,36 @@ export class NotificationHolderService { }) } + + PhoneClickNotification(ClickedNotificationObject) { + //alert("PhoneClickNotification") + + //alert(JSON.stringify(ClickedNotificationObject)) + const { hashCode, id } = this.notificationObject(ClickedNotificationObject) + + + + //alert(id) + //alert(JSON.stringify(this._notificationList)) + // let foundNotification = this._notificationList.find( (e) => { + // return e.hashCode == hashCode + // }) + + //if(foundNotification) { + // this.removeNotification(foundNotification) + //} else { + console.log({ ClickedNotificationObject, list: this._notificationList }) + + let foundNotification = this._notificationList.find((e) => { + return e.id == id + }) + + if (foundNotification) { + this.removeNotification(foundNotification) + } else { + console.log({ ClickedNotificationObject, list: this._notificationList }) + } + //} + } + }