fix chat open modal

This commit is contained in:
Lorito Tiago
2023-10-19 15:03:12 +01:00
parent 2a4796bb3d
commit 26b894ed1c
11 changed files with 976 additions and 831 deletions
+2 -2
View File
@@ -390,7 +390,7 @@
CODE_SIGN_ENTITLEMENTS = App/App.entitlements; CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
CODE_SIGN_STYLE = Manual; CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 47; CURRENT_PROJECT_VERSION = 61;
DEVELOPMENT_TEAM = ""; DEVELOPMENT_TEAM = "";
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = 94BRNM2LSS; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = 94BRNM2LSS;
INFOPLIST_FILE = App/Info.plist; INFOPLIST_FILE = App/Info.plist;
@@ -419,7 +419,7 @@
CODE_SIGN_ENTITLEMENTS = App/App.entitlements; CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
CODE_SIGN_STYLE = Manual; CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 47; CURRENT_PROJECT_VERSION = 61;
DEVELOPMENT_TEAM = ""; DEVELOPMENT_TEAM = "";
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = 94BRNM2LSS; "DEVELOPMENT_TEAM[sdk=iphoneos*]" = 94BRNM2LSS;
INFOPLIST_FILE = App/Info.plist; INFOPLIST_FILE = App/Info.plist;
+46 -7
View File
@@ -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 { ChatDebuggingPage } from 'src/app/shared/popover/chat-debugging/chat-debugging.page';
import { EventTrigger } from 'src/app/services/eventTrigger.service'; import { EventTrigger } from 'src/app/services/eventTrigger.service';
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.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'; import { Plugins } from '@capacitor/core';
const { App } = Plugins; const { App } = Plugins;
@@ -126,7 +126,8 @@ export class ChatPage implements OnInit {
private activatedRoute: ActivatedRoute, private activatedRoute: ActivatedRoute,
private eventTriger: EventTrigger, private eventTriger: EventTrigger,
private RochetChatConnectorService: RochetChatConnectorService, private RochetChatConnectorService: RochetChatConnectorService,
private zone: NgZone private zone: NgZone,
public RouteService: RouteService,
) { ) {
this.headers = new HttpHeaders(); this.headers = new HttpHeaders();
@@ -174,7 +175,6 @@ export class ChatPage implements OnInit {
} }
}); });
this.routeCheck()
} }
ngOnDestroy() { ngOnDestroy() {
@@ -189,14 +189,45 @@ export class ChatPage implements OnInit {
// Retry connecting or other reconnection logic can be added here. // Retry connecting or other reconnection logic can be added here.
} }
routeCheck() { firstEnter = true
routeCheck() {
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const roomId = urlParams.get('roomId'); const roomId = urlParams.get('roomId');
if (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) { if (room.isGroup) {
this.segment = 'Grupos' this.segment = 'Grupos'
this.openGroupMessagesPage(roomId) this.openGroupMessagesPage(roomId)
@@ -204,8 +235,17 @@ export class ChatPage implements OnInit {
this.segment = 'Contactos' this.segment = 'Contactos'
this.openMessagesPage(roomId) 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) => { modal.onDidDismiss().then((Data) => {
// console.log(Data,'daatatatat');
// let data = Data.data // let data = Data.data
// let roomId = data.roomId // let roomId = data.roomId
@@ -30,7 +30,8 @@
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " src="assets/icon/theme/gov/icons-user.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'gov' " src="assets/icon/theme/gov/icons-user.svg"></ion-icon>
</div> </div>
<div class="header-bottom-contacts" *ngIf="ChatSystemService.getGroupRoom(roomId)"> <div class="header-bottom-contacts" *ngIf="ChatSystemService.getGroupRoom(roomId)">
<ion-label class="contacts-list" *ngFor="let member of ChatSystemService.getGroupRoom(roomId).membersExcludeMe" > <ion-label class="contacts-list"
*ngFor="let member of ChatSystemService.getGroupRoom(roomId).membersExcludeMe">
{{member.name}}, {{member.name}},
</ion-label> </ion-label>
</div> </div>
@@ -39,6 +40,7 @@
<i class="far fa-clock font-15"></i> <i class="far fa-clock font-15"></i>
<ion-label class="font-15 pl-10" color="warning">{{roomCountDownDate}}</ion-label> <ion-label class="font-15 pl-10" color="warning">{{roomCountDownDate}}</ion-label>
</div> </div>
{{ RouteService.history }}
</div> </div>
</ion-toolbar> </ion-toolbar>
</ion-header> </ion-header>
@@ -51,24 +53,31 @@
<ion-label>Esta conversa passou a grupo</ion-label><br /> <ion-label>Esta conversa passou a grupo</ion-label><br />
<ion-label>A conversa original mantêm-se como chat individual</ion-label> <ion-label>A conversa original mantêm-se como chat individual</ion-label>
</div> </div>
<div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of ChatSystemService.getGroupRoom(roomId).messages; let last = last" [class.messages-list-item-wrapper-active]="msg._id == selectedMsgId"> <div class="messages-list-item-wrapper container-width-100"
<div class='message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}' *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'au' && msg.t != 'ru' && msg.msg !=''" (press)="handlePress(msg._id)" [class.dateLabel]="msg.dateLabel"> *ngFor="let msg of ChatSystemService.getGroupRoom(roomId).messages; let last = last"
[class.messages-list-item-wrapper-active]="msg._id == selectedMsgId">
<div class='message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}'
*ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'au' && msg.t != 'ru' && msg.msg !=''"
(press)="handlePress(msg._id)" [class.dateLabel]="msg.dateLabel">
<div class="title" *ngIf="!msg.dateLabel"> <div class="title" *ngIf="!msg.dateLabel">
<ion-label>{{msg.u.name ?? ""}}</ion-label> <ion-label>{{msg.u.name ?? ""}}</ion-label>
<span class="time">{{msg.time}}</span> <span class="time">{{msg.time}}</span>
</div> </div>
<div class="message"> <div class="message">
<pre *ngIf="msg.delate == false" class="message-box text ma-0 font-13-rem" style="font-size: 0.8125rem !important;" >{{msg.msg}}</pre> <pre *ngIf="msg.delate == false" class="message-box text ma-0 font-13-rem"
<pre *ngIf="msg.delate == true" class="message-box text ma-0 font-13-rem" style="font-size: 0.8125rem !important;" >{{msg.msg}}</pre> style="font-size: 0.8125rem !important;">{{msg.msg}}</pre>
<pre *ngIf="msg.delate == true" class="message-box text ma-0 font-13-rem"
style="font-size: 0.8125rem !important;">{{msg.msg}}</pre>
<ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName"> <ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName">
<span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10"> Enviado</span> <span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10">
Enviado</span>
<!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> -->
<span class="lido pl-10" *ngIf="msg.viewed.length >= 1" > Lido</span> <span class="lido pl-10" *ngIf="msg.viewed.length >= 1"> Lido</span>
<div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div> <div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div>
</ion-label> </ion-label>
{{last ? scrollToBottom() : ''}} {{last ? scrollToBottom() : ''}}
@@ -77,7 +86,10 @@
<div *ngIf="msg.file && msg.delate == false"> <div *ngIf="msg.file && msg.delate == false">
<div class='message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}' class='message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}' *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'ru' && msg.file.type != 'application/meeting'" (press)="handlePress(msg._id)"> <div class='message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}'
class='message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}'
*ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'ru' && msg.file.type != 'application/meeting'"
(press)="handlePress(msg._id)">
<div class="title"> <div class="title">
<ion-label>{{msg.u.name ?? ""}}</ion-label> <ion-label>{{msg.u.name ?? ""}}</ion-label>
<span class="time">{{msg.time}}</span> <span class="time">{{msg.time}}</span>
@@ -88,25 +100,34 @@
<div *ngIf="msg.file.type == 'application/img' && !msg.attachments[0].image_url"> <div *ngIf="msg.file.type == 'application/img' && !msg.attachments[0].image_url">
NOT UPLOADED NOT UPLOADED
</div> </div>
<div *ngIf="msg.file.type == 'application/img' && msg.attachments[0].image_url" (click)="openPreview(msg)"> <div *ngIf="msg.file.type == 'application/img' && msg.attachments[0].image_url"
(click)="openPreview(msg)">
<div *ngIf="!msg.attachments[0].image_url"> <div *ngIf="!msg.attachments[0].image_url">
<ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button"> <ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button">
<ion-icon name="image" class="file-icon"></ion-icon> <ion-icon name="image" class="file-icon"></ion-icon>
<ion-label>{{"Imagem"}}</ion-label> <ion-label>{{"Imagem"}}</ion-label>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && msg.downloadLoader == false && msg.uploadingFile == false && msg.downloadAttachmentsTemp == 0" class="icon-download" src="assets/icon/theme/{{ThemeService.currentTheme}}/icons-download.svg" slot="end"></ion-icon> <ion-icon
<ion-icon *ngIf="msg.downloadLoader == true || msg.uploadingFile == true " class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg" slot="end"></ion-icon> *ngIf="ThemeService.currentTheme == 'gov' && msg.downloadLoader == false && msg.uploadingFile == false && msg.downloadAttachmentsTemp == 0"
<ion-icon *ngIf="msg.downloadAttachments == false && msg.downloadAttachmentsTemp >= 1 && msg.downloadLoader == false" src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon> class="icon-download" src="assets/icon/theme/{{ThemeService.currentTheme}}/icons-download.svg"
slot="end"></ion-icon>
<ion-icon *ngIf="msg.downloadLoader == true || msg.uploadingFile == true " class="icon-download"
src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg" slot="end"></ion-icon>
<ion-icon
*ngIf="msg.downloadAttachments == false && msg.downloadAttachmentsTemp >= 1 && msg.downloadLoader == false"
src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon>
</ion-item> </ion-item>
</div> </div>
<img class="d-block width-100" *ngIf="msg.attachments[0].image_url" src="{{msg.attachments[0].image_url}}" alt="image" > <img class="d-block width-100" *ngIf="msg.attachments[0].image_url"
src="{{msg.attachments[0].image_url}}" alt="image">
<ion-icon *ngIf="msg.attachments[0].image_url == null" name="download-outline"></ion-icon> <ion-icon *ngIf="msg.attachments[0].image_url == null" name="download-outline"></ion-icon>
<ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName"> <ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName">
<span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10"> Enviado</span> <span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10">
Enviado</span>
<!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> -->
<span class="lido pl-10" *ngIf="msg.viewed.length >= 1" > Lido</span> <span class="lido pl-10" *ngIf="msg.viewed.length >= 1"> Lido</span>
<div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div> <div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div>
</ion-label> </ion-label>
</div> </div>
@@ -116,39 +137,64 @@
<div *ngIf="!msg.attachments[0].image_url"> <div *ngIf="!msg.attachments[0].image_url">
<ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button"> <ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button">
<ion-icon *ngIf="msg.attachments[0].type != 'webtrix'" name="document" class="file-icon"></ion-icon> <ion-icon *ngIf="msg.attachments[0].type != 'webtrix'" name="document"
<ion-icon *ngIf="msg.attachments[0].type == 'webtrix'" src="assets/icon/webtrix.svg" class="file-icon"></ion-icon> class="file-icon"></ion-icon>
<ion-icon *ngIf="msg.attachments[0].type == 'webtrix'" src="assets/icon/webtrix.svg"
class="file-icon"></ion-icon>
<ion-label>{{ file.title}}</ion-label> <ion-label>{{ file.title}}</ion-label>
<ion-icon *ngIf="ThemeService.currentTheme == 'default' && msg.attachments[0].type != 'webtrix' && !( msg.downloadLoader == true || msg.uploadingFile == true ) " class="icon-download" src="assets/icon/theme/default/icons-download.svg" slot="end"></ion-icon> <ion-icon
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && msg.attachments[0].type != 'webtrix' && !( msg.downloadLoader == true || msg.uploadingFile == true ) " class="icon-download" src="assets/icon/theme/gov/icons-download.svg" slot="end"></ion-icon> *ngIf="ThemeService.currentTheme == 'default' && msg.attachments[0].type != 'webtrix' && !( msg.downloadLoader == true || msg.uploadingFile == true ) "
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )" class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg" slot="end"></ion-icon> class="icon-download" src="assets/icon/theme/default/icons-download.svg"
slot="end"></ion-icon>
<ion-icon
*ngIf="ThemeService.currentTheme == 'gov' && msg.attachments[0].type != 'webtrix' && !( msg.downloadLoader == true || msg.uploadingFile == true ) "
class="icon-download" src="assets/icon/theme/gov/icons-download.svg" slot="end"></ion-icon>
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )"
class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg"
slot="end"></ion-icon>
</ion-item> </ion-item>
</div> </div>
<div *ngIf="msg.attachments[0].image_url"> <div *ngIf="msg.attachments[0].image_url">
<span *ngIf="msg.file.type"> <span *ngIf="msg.file.type">
<fa-icon *ngIf="msg.file.type == 'application/pdf'" icon="file-pdf" class="pdf-icon"></fa-icon> <fa-icon *ngIf="msg.file.type == 'application/pdf'" icon="file-pdf"
<fa-icon *ngIf="msg.file.type == 'application/word'" icon="file-word" class="word-icon"></fa-icon> class="pdf-icon"></fa-icon>
<fa-icon *ngIf="msg.file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'" icon="file-word" class="word-icon"></fa-icon> <fa-icon *ngIf="msg.file.type == 'application/word'" icon="file-word"
<fa-icon *ngIf="msg.file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'" icon="file-word" class="excel-icon"></fa-icon> class="word-icon"></fa-icon>
<ion-icon *ngIf="msg.file.type == 'application/webtrix'" src="assets/icon/webtrix.svg"></ion-icon> <fa-icon
*ngIf="msg.file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'"
icon="file-word" class="word-icon"></fa-icon>
<fa-icon
*ngIf="msg.file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'"
icon="file-word" class="excel-icon"></fa-icon>
<ion-icon *ngIf="msg.file.type == 'application/webtrix'"
src="assets/icon/webtrix.svg"></ion-icon>
</span> </span>
<ion-label class="file-title">{{file.title}}</ion-label> <ion-label class="file-title">{{file.title}}</ion-label>
</div> </div>
</div> </div>
</div> </div>
<div (click)="audioPreview(msg)" class="audio-contentainer" *ngIf="msg.file.type == 'application/audio' && !file.title_link"> <div (click)="audioPreview(msg)" class="audio-contentainer"
*ngIf="msg.file.type == 'application/audio' && !file.title_link">
<ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button"> <ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button">
<ion-icon name="mic-outline" class="file-icon"></ion-icon> <ion-icon name="mic-outline" class="file-icon"></ion-icon>
<ion-label>{{"Mensagem de voz"}}</ion-label> <ion-label>{{"Mensagem de voz"}}</ion-label>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && msg.downloadLoader == false && msg.uploadingFile == false && msg.downloadAttachmentsTemp == 0" class="icon-download" src="assets/icon/theme/{{ThemeService.currentTheme}}/icons-download.svg" slot="end"></ion-icon> <ion-icon
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )" class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg" slot="end"></ion-icon> *ngIf="ThemeService.currentTheme == 'gov' && msg.downloadLoader == false && msg.uploadingFile == false && msg.downloadAttachmentsTemp == 0"
<ion-icon *ngIf="msg.downloadAttachments == false && msg.downloadAttachmentsTemp >= 1 && msg.downloadLoader == false" src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon> class="icon-download" src="assets/icon/theme/{{ThemeService.currentTheme}}/icons-download.svg"
slot="end"></ion-icon>
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )"
class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg"
slot="end"></ion-icon>
<ion-icon
*ngIf="msg.downloadAttachments == false && msg.downloadAttachmentsTemp >= 1 && msg.downloadLoader == false"
src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon>
</ion-item> </ion-item>
</div> </div>
<div class="audio-contentainer" *ngIf="msg.file.type == 'application/audio' && file.title_link"> <div class="audio-contentainer" *ngIf="msg.file.type == 'application/audio' && file.title_link">
<audio [src]="file.title_link|safehtml" preload="metadata" class="d-flex width-100" controls controlsList="nodownload noplaybackrate"></audio> <audio [src]="file.title_link|safehtml" preload="metadata" class="d-flex width-100" controls
controlsList="nodownload noplaybackrate"></audio>
</div> </div>
<div class="file-details-optional add-attachment-bg-color"> <div class="file-details-optional add-attachment-bg-color">
<ion-label *ngIf="msg.file && msg.file != ''"> <ion-label *ngIf="msg.file && msg.file != ''">
@@ -158,12 +204,13 @@
</ion-label> </ion-label>
<ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName"> <ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName">
<span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10"> Enviado</span> <span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10">
Enviado</span>
<!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> -->
<span class="lido pl-10" *ngIf="msg.viewed.length >= 1" > Lido</span> <span class="lido pl-10" *ngIf="msg.viewed.length >= 1"> Lido</span>
<div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()"> Tentar</div> <div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()"> Tentar</div>
</ion-label> </ion-label>
</div> </div>
@@ -175,9 +222,12 @@
</div> </div>
<div *ngIf="msg.file.type == 'application/meeting'" class="info-meeting"> <div *ngIf="msg.file.type == 'application/meeting'" class="info-meeting">
<ion-label class="info-meeting-small">{{msg.u.name ?? ""}} criou esta reunião</ion-label><br /> <ion-label class="info-meeting-small">{{msg.u.name ?? ""}} criou esta reunião</ion-label><br />
<button (click)="goToEvent(msg.file)" class="btn-no-color info-meeting-normal"><ion-label class="info-meeting-normal">{{msg.file.subject}}</ion-label></button><br /> <button (click)="goToEvent(msg.file)" class="btn-no-color info-meeting-normal"><ion-label
<ion-label class="info-meeting-medium"><ion-icon name="calendar-outline"></ion-icon> De {{showDateDuration(msg.file.start_date)}} a {{showDateDuration(msg.file.end_date)}}</ion-label><br /> class="info-meeting-normal">{{msg.file.subject}}</ion-label></button><br />
<ion-label class="info-meeting-medium"><ion-icon></ion-icon><ion-icon name="location-outline"></ion-icon> {{msg.file.venue}}</ion-label><br /> <ion-label class="info-meeting-medium"><ion-icon name="calendar-outline"></ion-icon> De
{{showDateDuration(msg.file.start_date)}} a {{showDateDuration(msg.file.end_date)}}</ion-label><br />
<ion-label class="info-meeting-medium"><ion-icon></ion-icon><ion-icon name="location-outline"></ion-icon>
{{msg.file.venue}}</ion-label><br />
</div> </div>
</div> </div>
@@ -209,9 +259,9 @@
</div> </div>
{{last ? scrollToBottom() : ''}} {{last ? scrollToBottom() : ''}}
</div> </div>
<div *ngIf="msg.t == 'au' && msg.msg != sessionStore.user.UserName" > <div *ngIf="msg.t == 'au' && msg.msg != sessionStore.user.UserName">
<div *ngFor="let user of allUsers" > <div *ngFor="let user of allUsers">
<div *ngIf="msg.msg == user.username" class="info-text-leave"> <div *ngIf="msg.msg == user.username" class="info-text-leave">
<ion-label>Adicionou {{user.name}}</ion-label><br /> <ion-label>Adicionou {{user.name}}</ion-label><br />
</div> </div>
@@ -231,24 +281,24 @@
<ion-footer> <ion-footer>
<div class="typing" *ngIf="ChatSystemService.getGroupRoom(roomId).otherUserType == true"> <div class="typing" *ngIf="ChatSystemService.getGroupRoom(roomId).otherUserType == true">
<ngx-letters-avatar *ngIf="showAvatar" <ngx-letters-avatar *ngIf="showAvatar" [avatarName]="ChatSystemService.getGroupRoom(roomId).name" [width]="30"
[avatarName]= "ChatSystemService.getGroupRoom(roomId).name" [circular]="true" fontFamily="Roboto"></ngx-letters-avatar>
[width]="30"
[circular]="true"
fontFamily="Roboto"></ngx-letters-avatar>
{{ ChatSystemService.getGroupRoom(roomId).userThatIsTyping }} está a escrever... {{ ChatSystemService.getGroupRoom(roomId).userThatIsTyping }} está a escrever...
</div> </div>
<div class="width-100 pl-20 pr-20"> <div class="width-100 pl-20 pr-20">
<span *ngIf="!lastAudioRecorded">{{durationDisplay}}</span> <span *ngIf="!lastAudioRecorded">{{durationDisplay}}</span>
<audio [src]="audioRecorded" class="d-flex width-100 mt-10 mb-10" *ngIf="lastAudioRecorded" controls controlsList="nodownload noplaybackrate"></audio> <audio [src]="audioRecorded" class="d-flex width-100 mt-10 mb-10" *ngIf="lastAudioRecorded" controls
controlsList="nodownload noplaybackrate"></audio>
</div> </div>
<div class="container width-100 d-flex"> <div class="container width-100 d-flex">
<div> <div>
<button *ngIf="!recording && !lastAudioRecorded && allowTyping" class="btn-no-color" (click)="openChatOptions()"> <button *ngIf="!recording && !lastAudioRecorded && allowTyping" class="btn-no-color" (click)="openChatOptions()">
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="chat-icon-options" src="assets/images/icons-add.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="chat-icon-options"
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="chat-icon-options" src="assets/images/theme/gov/icons-add.svg"></ion-icon> src="assets/images/icons-add.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="chat-icon-options"
src="assets/images/theme/gov/icons-add.svg"></ion-icon>
</button> </button>
<button *ngIf="recording || lastAudioRecorded || !allowTyping" class="btn-no-color" (click)="deleteRecording()"> <button *ngIf="recording || lastAudioRecorded || !allowTyping" class="btn-no-color" (click)="deleteRecording()">
<fa-icon class="icon-size-27" icon="trash"></fa-icon> <fa-icon class="icon-size-27" icon="trash"></fa-icon>
@@ -256,7 +306,10 @@
</div> </div>
<div class="message-box width-80"> <div class="message-box width-80">
<div *ngIf="!recording && !lastAudioRecorded" class="type-message"> <div *ngIf="!recording && !lastAudioRecorded" class="type-message">
<ion-textarea *ngIf="allowTyping" autocomplete="on" autocorrect="on" spellcheck="true" clearOnEdit="true" placeholder="Escrever uma mensagem" auto-grow class="message-input" rows="1" [(ngModel)]="ChatSystemService.getGroupRoom(roomId).message" (ionChange)="ChatSystemService.getGroupRoom(roomId).sendTyping()"></ion-textarea> <ion-textarea *ngIf="allowTyping" autocomplete="on" autocorrect="on" spellcheck="true" clearOnEdit="true"
placeholder="Escrever uma mensagem" auto-grow class="message-input" rows="1"
[(ngModel)]="ChatSystemService.getGroupRoom(roomId).message"
(ionChange)="ChatSystemService.getGroupRoom(roomId).sendTyping()"></ion-textarea>
</div> </div>
<div *ngIf="recording" class="d-flex align-items-center justify-content-center"> <div *ngIf="recording" class="d-flex align-items-center justify-content-center">
<button (click)="stopRecording()" class="btn-no-color d-flex align-items-center justify-content-center"> <button (click)="stopRecording()" class="btn-no-color d-flex align-items-center justify-content-center">
@@ -265,17 +318,25 @@
</div> </div>
</div> </div>
<div> <div>
<button #recordbtn *ngIf="!ChatSystemService.getGroupRoom(roomId).message && !lastAudioRecorded" (click)="startRecording()" class="btn-no-color"> <button #recordbtn *ngIf="!ChatSystemService.getGroupRoom(roomId).message && !lastAudioRecorded"
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="chat-icon-send" src="assets/icon/theme/default/icons-chat-record-audio.svg"></ion-icon> (click)="startRecording()" class="btn-no-color">
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="chat-icon-send" src="assets/icon/theme/gov/icons-chat-record-audio.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="chat-icon-send"
src="assets/icon/theme/default/icons-chat-record-audio.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="chat-icon-send"
src="assets/icon/theme/gov/icons-chat-record-audio.svg"></ion-icon>
</button> </button>
<button *ngIf="ChatSystemService.getGroupRoom(roomId).message" class="btn-no-color" (click)="sendMessage()"> <button *ngIf="ChatSystemService.getGroupRoom(roomId).message" class="btn-no-color" (click)="sendMessage()">
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="chat-icon-send" src="assets/icon/icons-chat-send.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="chat-icon-send"
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="chat-icon-send" src="assets/icon/theme/gov/icons-chat-send.svg"></ion-icon> src="assets/icon/icons-chat-send.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="chat-icon-send"
src="assets/icon/theme/gov/icons-chat-send.svg"></ion-icon>
</button> </button>
<button *ngIf="!ChatSystemService.getGroupRoom(roomId).message && lastAudioRecorded" class="btn-no-color" (click)="sendAudio(lastAudioRecorded)"> <button *ngIf="!ChatSystemService.getGroupRoom(roomId).message && lastAudioRecorded" class="btn-no-color"
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="chat-icon-send" src="assets/icon/theme/gov/icons-chat-send.svg"></ion-icon> (click)="sendAudio(lastAudioRecorded)">
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="chat-icon-send" src="assets/icon/theme/gov/icons-chat-send.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="chat-icon-send"
src="assets/icon/theme/gov/icons-chat-send.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " class="chat-icon-send"
src="assets/icon/theme/gov/icons-chat-send.svg"></ion-icon>
</button> </button>
</div> </div>
</div> </div>
@@ -31,6 +31,7 @@ import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';
import { SessionStore } from 'src/app/store/session.service'; import { SessionStore } from 'src/app/store/session.service';
import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera'; import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { RouteService } from 'src/app/services/route.service';
@Component({ @Component({
selector: 'app-group-messages', selector: 'app-group-messages',
templateUrl: './group-messages.page.html', templateUrl: './group-messages.page.html',
@@ -102,6 +103,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
private sanitiser: DomSanitizer, private sanitiser: DomSanitizer,
private file: File, private file: File,
private fileOpener: FileOpener, private fileOpener: FileOpener,
public RouteService: RouteService,
) { ) {
this.ChatSystemService.getUser() this.ChatSystemService.getUser()
+69 -33
View File
@@ -1,4 +1,4 @@
<ion-header class="ion-no-border"> <ion-header class="ion-no-border" *ngIf="ChatSystemService.getDmRoom(roomId)">
<ion-toolbar class="header-toolbar"> <ion-toolbar class="header-toolbar">
<div class="main-header"> <div class="main-header">
<div class="header-top"> <div class="header-top">
@@ -11,7 +11,8 @@
<div class="middle-container" *ngIf="!showMessageOptions"> <div class="middle-container" *ngIf="!showMessageOptions">
<div class="middle"> <div class="middle">
<ion-label class="title">{{ChatSystemService.getDmRoom(roomId).name}}</ion-label> <ion-label class="title">{{ChatSystemService.getDmRoom(roomId).name}}</ion-label>
<span><ion-icon *ngIf="RochetChatConnectorService.isLogin" class="{{ ChatSystemService.getDmRoom(this.roomId).online }}" name="ellipse"></ion-icon></span> <span><ion-icon *ngIf="RochetChatConnectorService.isLogin"
class="{{ ChatSystemService.getDmRoom(this.roomId).online }}" name="ellipse"></ion-icon></span>
</div> </div>
</div> </div>
@@ -41,35 +42,37 @@
</ion-toolbar> </ion-toolbar>
</ion-header> </ion-header>
<ion-content> <ion-content *ngIf="ChatSystemService.getDmRoom(roomId)">
<div (click)="handleClick()" class="message-attachments messages" #scrollMe> <div (click)="handleClick()" class="message-attachments messages" #scrollMe>
<div class="messages-list-item-wrapper container-width-100 file" <div class="messages-list-item-wrapper container-width-100 file" (dragover)="onDragOver($event)"
(dragover)="onDragOver($event)"
(dragleave)="onDragLeave($event)" (dragleave)="onDragLeave($event)"
*ngFor="let msg of ChatSystemService.getDmRoom(this.roomId).messages; let last = last" *ngFor="let msg of ChatSystemService.getDmRoom(this.roomId).messages; let last = last"
[class.messages-list-item-wrapper-active]="msg._id == selectedMsgId"> [class.messages-list-item-wrapper-active]="msg._id == selectedMsgId">
<div (press)="handlePress(msg._id)" class='file message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}' <div (press)="handlePress(msg._id)"
*ngIf="msg.msg !=''" [class.dateLabel]="msg.dateLabel"> class='file message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}' *ngIf="msg.msg !=''"
[class.dateLabel]="msg.dateLabel">
<div class="title file" *ngIf="!msg.dateLabel"> <div class="title file" *ngIf="!msg.dateLabel">
<ion-label >{{msg.u.name}}</ion-label> <ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{msg.time}}</span> <span class="time">{{msg.time}}</span>
</div> </div>
<div> <div>
<div class="file"> <div class="file">
<pre *ngIf="msg.delate == false" class="message-box text ma-0 font-13-rem" style="font-size: 0.8125rem !important;" >{{msg.msg}}</pre> <pre *ngIf="msg.delate == false" class="message-box text ma-0 font-13-rem"
style="font-size: 0.8125rem !important;">{{msg.msg}}</pre>
<!-- <ion-label *ngIf="msg.delate == false" class="message-box">{{msg.msg}} </ion-label> --> <!-- <ion-label *ngIf="msg.delate == false" class="message-box">{{msg.msg}} </ion-label> -->
<ion-label *ngIf="msg.delate == true" class="flex-0">Apagou a mensagem</ion-label> <ion-label *ngIf="msg.delate == true" class="flex-0">Apagou a mensagem</ion-label>
<ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName"> <ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName">
<span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10"> Enviado</span> <span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10">
Enviado</span>
<!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> -->
<span class="lido pl-10" *ngIf="msg.viewed.length >= 1" > Lido</span> <span class="lido pl-10" *ngIf="msg.viewed.length >= 1"> Lido</span>
<div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div> <div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div>
</ion-label> </ion-label>
</div> </div>
@@ -79,7 +82,9 @@
<div *ngIf="msg.file && msg.delate == false"> <div *ngIf="msg.file && msg.delate == false">
<div (press)="handlePress(msg._id)" class='message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}' *ngIf="msg.file.type != 'application/meeting'"> <div (press)="handlePress(msg._id)"
class='message-container incoming-{{msg.u.username!=sessionStore.user.UserName}}'
*ngIf="msg.file.type != 'application/meeting'">
<div class="title"> <div class="title">
<ion-label>{{msg.u.name}}</ion-label> <ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{msg.time}}</span> <span class="time">{{msg.time}}</span>
@@ -92,45 +97,67 @@
<ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button"> <ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button">
<ion-icon name="image" class="file-icon"></ion-icon> <ion-icon name="image" class="file-icon"></ion-icon>
<ion-label>{{"Imagem"}}</ion-label> <ion-label>{{"Imagem"}}</ion-label>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && msg.downloadLoader == false && msg.uploadingFile == false && msg.downloadAttachmentsTemp == 0" class="icon-download" src="assets/icon/theme/{{ThemeService.currentTheme}}/icons-download.svg" slot="end"></ion-icon> <ion-icon
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )" class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg" slot="end"></ion-icon> *ngIf="ThemeService.currentTheme == 'gov' && msg.downloadLoader == false && msg.uploadingFile == false && msg.downloadAttachmentsTemp == 0"
<ion-icon *ngIf="msg.downloadAttachments == false && msg.downloadAttachmentsTemp >= 1 && msg.downloadLoader == false" src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon> class="icon-download" src="assets/icon/theme/{{ThemeService.currentTheme}}/icons-download.svg"
slot="end"></ion-icon>
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )"
class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg"
slot="end"></ion-icon>
<ion-icon
*ngIf="msg.downloadAttachments == false && msg.downloadAttachmentsTemp >= 1 && msg.downloadLoader == false"
src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon>
</ion-item> </ion-item>
</div> </div>
<img class="d-block width-100" *ngIf="msg.attachments[0].image_url" src="{{msg.attachments[0].image_url}}" alt="image"> <img class="d-block width-100" *ngIf="msg.attachments[0].image_url"
src="{{msg.attachments[0].image_url}}" alt="image">
<ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName"> <ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName">
<span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10"> Enviado</span> <span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10">
Enviado</span>
<!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> -->
<span class="lido pl-10" *ngIf="msg.viewed.length >= 1" > Lido</span> <span class="lido pl-10" *ngIf="msg.viewed.length >= 1"> Lido</span>
<div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div> <div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div>
</ion-label> </ion-label>
</div> </div>
<div *ngIf="msg.file.type != 'application/img'"> <div *ngIf="msg.file.type != 'application/img'">
<div class="file add-attachment-bg-color" *ngIf="msg.file.type != 'application/audio'"> <div class="file add-attachment-bg-color" *ngIf="msg.file.type != 'application/audio'">
<div (click)="docIndex(i); openPreview(msg)" class="file-details add-ellipsis cursor-pointer" *ngIf="msg.file"> <div (click)="docIndex(i); openPreview(msg)" class="file-details add-ellipsis cursor-pointer"
*ngIf="msg.file">
<div *ngIf="!msg.attachments[0].image_url"> <div *ngIf="!msg.attachments[0].image_url">
<ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button"> <ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button">
<ion-icon *ngIf="msg.attachments[0].type != 'webtrix'" name="document" class="file-icon"></ion-icon> <ion-icon *ngIf="msg.attachments[0].type != 'webtrix'" name="document"
<ion-icon *ngIf="msg.attachments[0].type == 'webtrix'" src="assets/icon/webtrix.svg" class="file-icon"></ion-icon> class="file-icon"></ion-icon>
<ion-icon *ngIf="msg.attachments[0].type == 'webtrix'" src="assets/icon/webtrix.svg"
class="file-icon"></ion-icon>
<ion-label>{{ file.title}}</ion-label> <ion-label>{{ file.title}}</ion-label>
<ion-icon *ngIf="ThemeService.currentTheme == 'default' && msg.attachments[0].type != 'webtrix' && !( msg.downloadLoader == true || msg.uploadingFile == true ) " class="icon-download" src="assets/icon/theme/default/icons-download.svg" slot="end"></ion-icon> <ion-icon
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && msg.attachments[0].type != 'webtrix' && !( msg.downloadLoader == true || msg.uploadingFile == true ) " class="icon-download" src="assets/icon/theme/gov/icons-download.svg" slot="end"></ion-icon> *ngIf="ThemeService.currentTheme == 'default' && msg.attachments[0].type != 'webtrix' && !( msg.downloadLoader == true || msg.uploadingFile == true ) "
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )" class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg" slot="end"></ion-icon> class="icon-download" src="assets/icon/theme/default/icons-download.svg"
slot="end"></ion-icon>
<ion-icon
*ngIf="ThemeService.currentTheme == 'gov' && msg.attachments[0].type != 'webtrix' && !( msg.downloadLoader == true || msg.uploadingFile == true ) "
class="icon-download" src="assets/icon/theme/gov/icons-download.svg" slot="end"></ion-icon>
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )"
class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg"
slot="end"></ion-icon>
</ion-item> </ion-item>
</div> </div>
<div *ngIf="msg.attachments[0].image_url"> <div *ngIf="msg.attachments[0].image_url">
<span *ngIf="msg.file.type"> <span *ngIf="msg.file.type">
<fa-icon *ngIf="msg.file.type == 'application/pdf'" icon="file-pdf" class="pdf-icon"></fa-icon> <fa-icon *ngIf="msg.file.type == 'application/pdf'" icon="file-pdf"
<fa-icon *ngIf="msg.file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'" icon="file-word" class="word-icon"></fa-icon> class="pdf-icon"></fa-icon>
<fa-icon
*ngIf="msg.file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'"
icon="file-word" class="word-icon"></fa-icon>
<fa-icon *ngIf="msg.file.type == 'application/word'" icon="file-word" class="word-icon"> <fa-icon *ngIf="msg.file.type == 'application/word'" icon="file-word" class="word-icon">
</fa-icon> </fa-icon>
<fa-icon <fa-icon
@@ -144,13 +171,21 @@
<!-- <ion-progress-bar [type]="'indeterminate'" *ngIf="downloadLoader"></ion-progress-bar> --> <!-- <ion-progress-bar [type]="'indeterminate'" *ngIf="downloadLoader"></ion-progress-bar> -->
</div> </div>
</div> </div>
<div (click)="audioPreview(msg)" class="audio-contentainer" *ngIf="msg.file.type == 'application/audio' && !file.title_link"> <div (click)="audioPreview(msg)" class="audio-contentainer"
*ngIf="msg.file.type == 'application/audio' && !file.title_link">
<ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button"> <ion-item class="add-attachment-bg-color" shape="round" lines="none" type="button">
<ion-icon name="mic-outline" class="file-icon"></ion-icon> <ion-icon name="mic-outline" class="file-icon"></ion-icon>
<ion-label>{{"Mensagem de voz"}}</ion-label> <ion-label>{{"Mensagem de voz"}}</ion-label>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && msg.downloadLoader == false && msg.uploadingFile == false && msg.downloadAttachmentsTemp == 0" class="icon-download" src="assets/icon/theme/{{ThemeService.currentTheme}}/icons-download.svg" slot="end"></ion-icon> <ion-icon
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )" class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg" slot="end"></ion-icon> *ngIf="ThemeService.currentTheme == 'gov' && msg.downloadLoader == false && msg.uploadingFile == false && msg.downloadAttachmentsTemp == 0"
<ion-icon *ngIf="msg.downloadAttachments == false && msg.downloadAttachmentsTemp >= 1 && msg.downloadLoader == false" src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon> class="icon-download" src="assets/icon/theme/{{ThemeService.currentTheme}}/icons-download.svg"
slot="end"></ion-icon>
<ion-icon *ngIf="( msg.downloadLoader == true || msg.uploadingFile == true )"
class="icon-download" src="assets/gif/theme/{{ThemeService.currentTheme}}/Blocks-loader.svg"
slot="end"></ion-icon>
<ion-icon
*ngIf="msg.downloadAttachments == false && msg.downloadAttachmentsTemp >= 1 && msg.downloadLoader == false"
src="assets/images/retry-svgrepo-com.svg" class="icon-download font-12"> </ion-icon>
</ion-item> </ion-item>
</div> </div>
<div class="file audio-contentainer" *ngIf="msg.file.type == 'application/audio' && file.title_link"> <div class="file audio-contentainer" *ngIf="msg.file.type == 'application/audio' && file.title_link">
@@ -166,12 +201,13 @@
<ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName"> <ion-label class="float-status-all float-status" *ngIf="msg.u.username==sessionStore.user.UserName">
<span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10"> Enviado</span> <span *ngIf="msg.online == true && !msg.manualRetry && msg.viewed == 0" class="enviado pl-10">
Enviado</span>
<!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == false && !msg.manualRetry" src="assets/images/clock-regular.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend == true && msg.received.length == 0 && msg.viewed.length == 0" src="assets/images/check-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.messageSend && msg.received.length >= 1 && msg.viewed.length == 0" src="assets/images/check-double-solid.svg"></ion-icon> -->
<!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> --> <!-- <ion-icon *ngIf="msg.viewed.length >= 1" src="assets/images/check-double-solid -viewed.svg"></ion-icon> -->
<span class="lido pl-10" *ngIf="msg.viewed.length >= 1" > Lido</span> <span class="lido pl-10" *ngIf="msg.viewed.length >= 1"> Lido</span>
<div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div> <div *ngIf="msg.manualRetry" class="try pl-10" (click)="msg.send()">Tentar</div>
</ion-label> </ion-label>
@@ -213,7 +249,7 @@
</ion-content> </ion-content>
<ion-footer (click)="ChatSystemService.getDmRoom(roomId).sendReadMessage()"> <ion-footer *ngIf="ChatSystemService.getDmRoom(roomId)" (click)="ChatSystemService.getDmRoom(roomId).sendReadMessage()">
<div class="typing" *ngIf="ChatSystemService.getDmRoom(roomId).otherUserType == true"> <div class="typing" *ngIf="ChatSystemService.getDmRoom(roomId).otherUserType == true">
<ngx-letters-avatar [avatarName]="ChatSystemService.getGroupRoom(roomId).name" [width]="30" [circular]="true" <ngx-letters-avatar [avatarName]="ChatSystemService.getGroupRoom(roomId).name" [width]="30" [circular]="true"
+18 -7
View File
@@ -118,6 +118,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
private router: Router, private router: Router,
public RochetChatConnectorService: RochetChatConnectorService, public RochetChatConnectorService: RochetChatConnectorService,
) { ) {
try {
this.loggedUser = SessionStore.user.ChatData['data']; this.loggedUser = SessionStore.user.ChatData['data'];
this.roomId = this.navParams.get('roomId'); this.roomId = this.navParams.get('roomId');
@@ -136,11 +139,15 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
setTimeout(() => { setTimeout(() => {
this.scrollToBottomClicked() this.scrollToBottomClicked()
}, 150) }, 150)
} catch (error) {
//alert(error)
}
} }
ngOnInit() { ngOnInit() {
try {
console.log(this.router.url); console.log(this.router.url);
this.createDirectoryImage() this.createDirectoryImage()
// this.chatService.refreshtoken(); // this.chatService.refreshtoken();
@@ -151,6 +158,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}) })
this.getChatMembers(); this.getChatMembers();
} catch (error) {
//alert(error)
}
} }
@@ -175,8 +186,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
longpress.enable(); longpress.enable();
} }
onDragOver(e?) {} onDragOver(e?) { }
onDragLeave(e?) {} onDragLeave(e?) { }
calculateDuration() { calculateDuration() {
if (!this.recording) { if (!this.recording) {
@@ -688,7 +699,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
} }
// write the ArrayBuffer to a blob, and you're done // 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; return blob;
} }
@@ -810,7 +821,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
_getBase64(file) { _getBase64(file) {
return new Promise((resolve, reject)=>{ return new Promise((resolve, reject) => {
var reader = new FileReader(); var reader = new FileReader();
reader.readAsDataURL(file); reader.readAsDataURL(file);
reader.onload = function () { reader.onload = function () {
@@ -844,14 +855,14 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
if (file.type != "application/img" && file.type != "image/png" && file.type != "image/jpeg" && file.type != "image/gif") { 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.error(error);
}))); })));
console.log(encodedData) console.log(encodedData)
const blob = this.fileService.base64toBlob(encodedData, file.type) const blob = this.fileService.base64toBlob(encodedData, file.type)
console.log('BLOB BLOB',blob) console.log('BLOB BLOB', blob)
const formData = new FormData(); const formData = new FormData();
formData.append('blobFile', blob); formData.append('blobFile', blob);
+47 -149
View File
@@ -114,8 +114,11 @@ export class ChatSystemService {
document.addEventListener('resume', () => { document.addEventListener('resume', () => {
this.RochetChatConnectorService.setStatus('online') this.RochetChatConnectorService.setStatus('online')
if (this._dm?.length == 0 && this._group?.length == 0) { if (this._dm?.length == 0 && this._group?.length == 0) {
if (SessionStore.user?.ChatData?.data) {
this.getAllRooms(); this.getAllRooms();
} }
}
}); });
if (!this.platform.is('desktop')) { if (!this.platform.is('desktop')) {
@@ -124,11 +127,15 @@ export class ChatSystemService {
// The app is in the foreground. // The app is in the foreground.
console.log('App is in the foreground'); console.log('App is in the foreground');
if (SessionStore.user?.ChatData?.data) {
this.currentRoom?.loadHistory({ forceUpdate: true }) this.currentRoom?.loadHistory({ forceUpdate: true })
}
setTimeout(() => { setTimeout(() => {
if (SessionStore.user?.ChatData?.data) {
this.subscribeToRoom() this.subscribeToRoom()
this.RochetChatConnectorService.setStatus('online') this.RochetChatConnectorService.setStatus('online')
}
}, 1000); }, 1000);
/* this.reloadComponent(true) */ /* this.reloadComponent(true) */
@@ -150,6 +157,7 @@ export class ChatSystemService {
private async ReLoadChat() { private async ReLoadChat() {
if (SessionStore.user?.ChatData?.data) {
this.getUserStatus(); this.getUserStatus();
await this.chatService.refreshtoken(); await this.chatService.refreshtoken();
@@ -158,7 +166,7 @@ export class ChatSystemService {
await this.restoreRooms(); await this.restoreRooms();
await this.getAllRooms(); await this.getAllRooms();
this.subscribeToRoom(); this.subscribeToRoom();
}
// //
} }
@@ -263,90 +271,23 @@ export class ChatSystemService {
for (let roomData of this.sortArrayISODate(_rooms)) { for (let roomData of this.sortArrayISODate(_rooms)) {
const roomId = this.getRoomId(roomData); const roomId = this.getRoomId(roomData);
if (roomData.t == 'd') { 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); await this.prepareRoom(roomData);
} else { } else {
if (roomData.t === 'p') { 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); await this.prepareRoom(roomData);
} }
else { 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); await this.prepareRoom(roomData);
} }
} }
if (roomId == roomIdCallback) { if (roomId == roomIdCallback) {
callback() callback()
} }
index++; index++;
} }
} }
@@ -362,7 +303,6 @@ export class ChatSystemService {
async getRoom(_rooms: any) { async getRoom(_rooms: any) {
this.loadingWholeList = true this.loadingWholeList = true
let index = 0 let index = 0
if (_rooms) { if (_rooms) {
@@ -374,80 +314,17 @@ export class ChatSystemService {
for (let roomData of this.sortArrayISODate(_rooms)) { for (let roomData of this.sortArrayISODate(_rooms)) {
const roomId = this.getRoomId(roomData);
if (roomData.t == 'd') { 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); await this.prepareRoom(roomData);
} else { } else {
if (roomData.t === 'p') { 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); await this.prepareRoom(roomData);
} }
else { 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); await this.prepareRoom(roomData);
} }
@@ -477,6 +354,8 @@ export class ChatSystemService {
*/ */
subscribeToRoom() { subscribeToRoom() {
if (SessionStore.user?.ChatData?.data) {
for (const id in this.dm) { for (const id in this.dm) {
this.defaultSubtribe(id) this.defaultSubtribe(id)
} }
@@ -488,6 +367,13 @@ export class ChatSystemService {
this.RochetChatConnectorService.streamNotifyLogged().then((subscription => { })) this.RochetChatConnectorService.streamNotifyLogged().then((subscription => { }))
this.RochetChatConnectorService.subStreamMessageUser().then((subscription => { })) this.RochetChatConnectorService.subStreamMessageUser().then((subscription => { }))
} else {
setTimeout(() => {
throw ('No chat data');
}, 1000)
}
} }
/** /**
@@ -576,13 +462,20 @@ export class ChatSystemService {
lastMessage: this.getRoomLastMessage(roomData), lastMessage: this.getRoomLastMessage(roomData),
_updatedAt: new Date(roomData._updatedAt || roomData._updatedAt['$date']), _updatedAt: new Date(roomData._updatedAt || roomData._updatedAt['$date']),
u: roomData.u || {}, u: roomData.u || {},
members: roomData.members, members: [],
membersExcludeMe: roomData.membersExcludeMe membersExcludeMe: []
} }
let roomId = this.getRoomId(roomData); 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 // create room
if (!this.roomExist(roomId)) { 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) 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,25 +648,32 @@ export class ChatSystemService {
getRoomName(roomData: room): string { getRoomName(roomData: room): string {
if (this.isIndividual(roomData)) { if (this.isIndividual(roomData)) {
const names: String[] = roomData.usernames 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 { try {
const firstName = capitalizeTxt(roomName.split('.')[0]) const firstName = capitalizeTxt(username.split('.')[0])
const lastName = capitalizeTxt(roomName.split('.')[1]) const lastName = capitalizeTxt(username.split('.')[1])
return firstName + ' ' + lastName return firstName + ' ' + lastName
} catch (e) { } catch (error) {
return roomData['membersExcludeMe'][0].name 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 { } else {
return 'Sem nome' if (roomData.t === 'p') {
return 'Loading'
}
else {
return 'Loading'
}
} }
} else { } else {
return roomData.fname return roomData.fname
@@ -849,12 +749,10 @@ export class ChatSystemService {
async createGroup(name) { async createGroup(name) {
const res: any = await this.createPrivateRoom(name, SessionStore.user.UserName, {}); const res: any = await this.createPrivateRoom(name, SessionStore.user.UserName, {});
console.log('room is created', res)
if (res?.result?.rid) { if (res?.result?.rid) {
try { try {
await this.getAllRooms(); await this.getAllRooms();
} catch (e) { } } catch (e) { }
console.log('room is loaded')
return res return res
} else { } else {
return res return res
@@ -24,7 +24,7 @@ export class RochetChatConnectorService {
connect() { connect() {
// dont connect if is already connected // dont connect if is already connected
if(this.ws.connected == true) { if (this.ws.connected == true) {
return false return false
} }
@@ -35,29 +35,29 @@ export class RochetChatConnectorService {
version: "1", version: "1",
support: ["1"] support: ["1"]
} }
this.ws.send({message, loginRequired: false, requestId: 'connectMessage'}) this.ws.send({ message, loginRequired: false, requestId: 'connectMessage' })
this.ws.send({message:{msg:"pong"}, loginRequired: false, requestId: 'connectPong'}) this.ws.send({ message: { msg: "pong" }, loginRequired: false, requestId: 'connectPong' })
this.ws.registerCallback({ this.ws.registerCallback({
type:'Onmessage', type: 'Onmessage',
key:'ping-pong', key: 'ping-pong',
funx:(message: any) => { funx: (message: any) => {
if(message.msg == "ping") { if (message.msg == "ping") {
this.ws.send({message:{msg:"pong"}, loginRequired: false}) this.ws.send({ message: { msg: "pong" }, loginRequired: false })
} }
} }
}) })
} }
wsSend({message, requestId = uuidv4(), loginRequired = true}:send) { wsSend({ message, requestId = uuidv4(), loginRequired = true }: send) {
this.ws.send({message:{msg:"pong"}, loginRequired: false}) this.ws.send({ message: { msg: "pong" }, loginRequired: false })
} }
login() { login() {
// dont login if is already login // dont login if is already login
if(this.isLogin == true) { if (this.isLogin == true) {
return new Promise((resolve, reject)=>{ return new Promise((resolve, reject) => {
resolve(this.loginResponse) resolve(this.loginResponse)
}) })
} }
@@ -75,22 +75,23 @@ export class RochetChatConnectorService {
} }
] ]
} }
this.ws.send({message, requestId: 'login', loginRequired: false}) this.ws.send({ message, requestId: 'login', loginRequired: false })
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// //
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
type: 'Onmessage', funx: (message) => {
// //
if(message.id == requestId ) { // same request send if (message.id == requestId) { // same request send
// //
// //
if(message.result) { if (message.result) {
if(message.result.token) { if (message.result.token) {
this.isLogin = true this.isLogin = true
this.loginResponse = message this.loginResponse = message
setTimeout(()=>{ setTimeout(() => {
this.ws.wsMsgQueue() this.ws.wsMsgQueue()
}, 10) }, 10)
@@ -107,7 +108,8 @@ export class RochetChatConnectorService {
return true return true
} }
}}) }
})
}); });
} }
@@ -121,18 +123,20 @@ export class RochetChatConnectorService {
"msg": "method", "msg": "method",
"method": "rooms/get", "method": "rooms/get",
"id": requestId, "id": requestId,
"params": [ { "$date": 1480377601 } ] "params": [{ "$date": 1480377601 }]
} }
this.ws.send({message, requestId}) this.ws.send({ message, requestId })
return new Promise<Rooms>((resolve, reject) => { return new Promise<Rooms>((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -142,21 +146,23 @@ export class RochetChatConnectorService {
const requestId = uuidv4() const requestId = uuidv4()
const message = { const message = {
"msg":"method", "msg": "method",
"method":"readMessages", "method": "readMessages",
"params": [roomId, []], "params": [roomId, []],
"id": requestId "id": requestId
} }
this.ws.send({message, requestId}) this.ws.send({ message, requestId })
return new Promise<Rooms>((resolve, reject) => { return new Promise<Rooms>((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -176,18 +182,20 @@ export class RochetChatConnectorService {
{ {
"limit": 100, "limit": 100,
"skip": 0 "skip": 0
} ] }]
} }
this.ws.send({message, requestId}) this.ws.send({ message, requestId })
return new Promise<Rooms>((resolve, reject) => { return new Promise<Rooms>((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -198,7 +206,7 @@ export class RochetChatConnectorService {
} }
// send message to room // 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()
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) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
resolve({message, requestId}) if (message.id == requestId) { // same request send
resolve({ message, requestId })
return true return true
} }
}}) }
})
}); });
} }
@@ -240,15 +250,17 @@ export class RochetChatConnectorService {
params: [messageObject] params: [messageObject]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
resolve({message, requestId}) if (message.id == requestId) { // same request send
resolve({ message, requestId })
return true return true
} }
}}) }
})
}) })
} }
@@ -266,15 +278,17 @@ export class RochetChatConnectorService {
] ]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -292,15 +306,17 @@ export class RochetChatConnectorService {
] ]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -315,21 +331,23 @@ export class RochetChatConnectorService {
params: [roomId] params: [roomId]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
// //
return true return true
} }
}}) }
})
}); });
} }
joinRoom() {} joinRoom() { }
deleteMessage(msgId) { deleteMessage(msgId) {
//const requestId = uuidv4(); //const requestId = uuidv4();
@@ -338,18 +356,20 @@ export class RochetChatConnectorService {
msg: "method", msg: "method",
method: "deleteMessage", method: "deleteMessage",
id: requestId, id: requestId,
params:[{"_id":msgId}] params: [{ "_id": msgId }]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise ((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message) =>{ this.ws.registerCallback({
if(message.id == requestId ){ type: 'Onmessage', funx: (message) => {
if (message.id == requestId) {
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -366,25 +386,27 @@ export class RochetChatConnectorService {
false, false,
customFields, customFields,
{ {
"broadcast":false, "broadcast": false,
"encrypted":false "encrypted": false
} }
] ]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
sendStreamNotifyRoom(roomId : string, username, event: 'typing', param: any) { sendStreamNotifyRoom(roomId: string, username, event: 'typing', param: any) {
const requestId = uuidv4() 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) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
subStreamNotifyRoom(roomId : string , event: 'typing' | 'deleteMessage' | 'readMessage', param: any) { subStreamNotifyRoom(roomId: string, event: 'typing' | 'deleteMessage' | 'readMessage', param: any) {
const requestId = uuidv4() const requestId = uuidv4()
@@ -421,22 +445,24 @@ export class RochetChatConnectorService {
msg: "sub", msg: "sub",
id: requestId, id: requestId,
name: "stream-notify-room", name: "stream-notify-room",
params:[ params: [
`${roomId}/${event}`, `${roomId}/${event}`,
param param
] ]
} }
this.ws.send({message, requestId}) this.ws.send({ message, requestId })
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -450,22 +476,24 @@ export class RochetChatConnectorService {
msg: "sub", msg: "sub",
id: requestId, id: requestId,
name: "stream-notify-user", name: "stream-notify-user",
params:[ params: [
`${SessionStore.user.ChatData.data.userId}/notification`, `${SessionStore.user.ChatData.data.userId}/notification`,
param param
] ]
} }
this.ws.send({message, requestId}) this.ws.send({ message, requestId })
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -473,48 +501,53 @@ export class RochetChatConnectorService {
subStreamMessageUser(param?: any) { subStreamMessageUser(param?: any) {
const requestId = uuidv4() const requestId = uuidv4()
try {
let message = { let message = {
msg: "sub", msg: "sub",
id: requestId, id: requestId,
name: "stream-notify-user", name: "stream-notify-user",
params:[ params: [
`${SessionStore.user.ChatData.data.userId}/message`, `${SessionStore.user.ChatData.data.userId}/message`,
param param
] ]
} }
this.ws.send({message, requestId}) this.ws.send({ message, requestId })
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} catch (error) {
throw (SessionStore)
}
} }
receiveStreamNotifyRoom(funx: Function) { receiveStreamNotifyRoom(funx: Function) {
this.ws.registerCallback({ this.ws.registerCallback({
type:'Onmessage', type: 'Onmessage',
funx:(message)=> { funx: (message) => {
if(message.collection == "stream-notify-room" && message.msg == 'changed') { if (message.collection == "stream-notify-room" && message.msg == 'changed') {
funx(message) funx(message)
} }
}}) }
})
} }
getUserStatus(funx:Function){ getUserStatus(funx: Function) {
this.ws.registerCallback({ this.ws.registerCallback({
type:'Onmessage', type: 'Onmessage',
funx:(message)=>{ funx: (message) => {
if(message.msg == 'changed' && message.collection == "stream-notify-logged") { if (message.msg == 'changed' && message.collection == "stream-notify-logged") {
funx(message) funx(message)
} }
} }
@@ -540,16 +573,18 @@ export class RochetChatConnectorService {
] ]
} }
this.ws.send({message, requestId: 'loadHistory'}) this.ws.send({ message, requestId: 'loadHistory' })
return new Promise<chatHistory>((resolve, reject) => { return new Promise<chatHistory>((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
type: 'Onmessage', funx: (message) => {
// //
if(message.id == requestId ) { // same request send if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -562,15 +597,15 @@ export class RochetChatConnectorService {
msg: "method", msg: "method",
method: `UserPresence:setDefaultStatus`, method: `UserPresence:setDefaultStatus`,
id: requestId, 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() const requestId = uuidv4()
@@ -578,37 +613,39 @@ export class RochetChatConnectorService {
"msg": "sub", "msg": "sub",
"id": requestId, "id": requestId,
"name": "stream-notify-room", "name": "stream-notify-room",
"params":[ "params": [
`${roomId}/event`, `${roomId}/event`,
false false
] ]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.msg == 'ready' || deepFind(message, 'subs.0') == requestId) { // same request send type: 'Onmessage', funx: (message) => {
if (message.msg == 'ready' || deepFind(message, 'subs.0') == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
updateRoomEventss(roomId, collection:string, funx: Function, ) { updateRoomEventss(roomId, collection: string, funx: Function,) {
this.ws.registerCallback({ this.ws.registerCallback({
type:'Onmessage', type: 'Onmessage',
funx:(message)=>{ funx: (message) => {
// //
if(message.msg =='changed' && message.collection == collection) { if (message.msg == 'changed' && message.collection == collection) {
if(message.fields.args[0].rid == roomId) { if (message.fields.args[0].rid == roomId) {
funx(message) funx(message)
} }
else if(message.fields.eventName ==`${roomId}/deleteMessage`){ else if (message.fields.eventName == `${roomId}/deleteMessage`) {
funx(message) 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 = { const message = {
"msg": "sub", "msg": "sub",
"id": requestId, "id": requestId,
"name": "stream-room-messages", "name": "stream-room-messages",
"params":[ "params": [
`${roomId}`, `${roomId}`,
false false
] ]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise((resolve, reject) => { 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 if (message.id == requestId || message?.subs?.[0] == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
@@ -652,25 +691,27 @@ export class RochetChatConnectorService {
"msg": "sub", "msg": "sub",
"id": requestId, "id": requestId,
"name": "stream-notify-logged", "name": "stream-notify-logged",
"params":[ "params": [
"user-status", "user-status",
false false
] ]
} }
this.ws.send({message, requestId}); this.ws.send({ message, requestId });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
streamNotifyRoom(roomId : string) { streamNotifyRoom(roomId: string) {
const requestId = uuidv4() 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) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
streamNotifyRoomDeleteMessage(roomId:string) { streamNotifyRoomDeleteMessage(roomId: string) {
const requestId = uuidv4() 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) => { return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ this.ws.registerCallback({
if(message.id == requestId ) { // same request send type: 'Onmessage', funx: (message) => {
if (message.id == requestId) { // same request send
resolve(message) resolve(message)
return true return true
} }
}}) }
})
}); });
} }
registerCallback(data:wsCallbacksParams) { registerCallback(data: wsCallbacksParams) {
return this.ws.registerCallback(data) return this.ws.registerCallback(data)
} }
// socket class ================================================================== // socket class ==================================================================
private socket!: WebSocket; private socket!: WebSocket;
private wsMsgQueue : {[key: string]: msgQueue} = {} private wsMsgQueue: { [key: string]: msgQueue } = {}
private wsCallbacks: {[key: string]: wsCallbacksParams} = {} private wsCallbacks: { [key: string]: wsCallbacksParams } = {}
private wsReconnect = 0 private wsReconnect = 0
private n = 0 private n = 0
ws = { ws = {
connected: false, connected: false,
registerCallback:(params: wsCallbacksParams) => { registerCallback: (params: wsCallbacksParams) => {
let id = params.requestId || params.key || uuidv4() let id = params.requestId || params.key || uuidv4()
// //
@@ -747,7 +792,7 @@ export class RochetChatConnectorService {
this.n++ this.n++
return id return id
}, },
connect:()=> { connect: () => {
this.socket = new WebSocket(environment.apiWsChatUrl); this.socket = new WebSocket(environment.apiWsChatUrl);
// bind function // bind function
this.socket.onopen = this.ws.onopen; this.socket.onopen = this.ws.onopen;
@@ -756,24 +801,24 @@ export class RochetChatConnectorService {
this.socket.onerror = this.ws.onerror; this.socket.onerror = this.ws.onerror;
}, },
onopen: async ()=> { onopen: async () => {
this.ws.connected = true this.ws.connected = true
this.backgroundservice.online(); this.backgroundservice.online();
setTimeout(()=>{ setTimeout(() => {
this.ws.wsMsgQueue() this.ws.wsMsgQueue()
}, 10) }, 10)
console.log('rec conect') console.log('rec conect')
if(this.wsReconnect >= 1) { if (this.wsReconnect >= 1) {
for (const [key, value] of Object.entries(this.wsCallbacks)) { for (const [key, value] of Object.entries(this.wsCallbacks)) {
if(value.type== 'reConnect') { if (value.type == 'reConnect') {
const dontRepeat = await value.funx() const dontRepeat = await value.funx()
if(dontRepeat) { if (dontRepeat) {
this.n-- this.n--
delete this.wsCallbacks[key] delete this.wsCallbacks[key]
} }
@@ -785,28 +830,28 @@ export class RochetChatConnectorService {
this.wsReconnect++; this.wsReconnect++;
}, },
wsMsgQueue:()=> { wsMsgQueue: () => {
for (const [key, item] of Object.entries(this.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); this.ws.send(item);
delete this.wsMsgQueue[key] delete this.wsMsgQueue[key]
} else if(item.loginRequired == false) { } else if (item.loginRequired == false) {
// //
this.ws.send(item); this.ws.send(item);
delete this.wsMsgQueue[key] 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 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 { } else {
let messageStr = JSON.stringify(message) let messageStr = JSON.stringify(message)
this.socket.send(messageStr) this.socket.send(messageStr)
@@ -814,17 +859,17 @@ export class RochetChatConnectorService {
return requestId return requestId
}, },
onmessage: async (event: any)=> { onmessage: async (event: any) => {
this.backgroundservice.online(); this.backgroundservice.online();
const data = JSON.parse(event.data) const data = JSON.parse(event.data)
for (const [key, value] of Object.entries(this.wsCallbacks)) { for (const [key, value] of Object.entries(this.wsCallbacks)) {
if(value.type== 'Onmessage') { if (value.type == 'Onmessage') {
const dontRepeat = await value.funx(data) const dontRepeat = await value.funx(data)
if(dontRepeat) { if (dontRepeat) {
delete this.wsCallbacks[key] delete this.wsCallbacks[key]
this.n-- this.n--
} }
@@ -835,7 +880,7 @@ export class RochetChatConnectorService {
}, },
onclose: async (event: any)=> { onclose: async (event: any) => {
this.ws.connected = false this.ws.connected = false
this.isLogin = false this.isLogin = false
@@ -844,10 +889,10 @@ export class RochetChatConnectorService {
this.login() this.login()
for (const [key, value] of Object.entries(this.wsCallbacks)) { for (const [key, value] of Object.entries(this.wsCallbacks)) {
if(value.type == 'Offline') { if (value.type == 'Offline') {
const dontRepeat = await value.funx() const dontRepeat = await value.funx()
if(dontRepeat) { if (dontRepeat) {
delete this.wsCallbacks[key] delete this.wsCallbacks[key]
this.n-- this.n--
} }
@@ -862,13 +907,13 @@ export class RochetChatConnectorService {
onerror: (event: any) => { onerror: (event: any) => {
}, },
disconnect:() => { disconnect: () => {
if(this.socket) { if (this.socket) {
this.socket.onopen = (event: any) => {} this.socket.onopen = (event: any) => { }
this.socket.onmessage = (event: any) => {} this.socket.onmessage = (event: any) => { }
this.socket.onclose = (event: any) => {} this.socket.onclose = (event: any) => { }
this.socket.onerror = (event: any) => {} this.socket.onerror = (event: any) => { }
this.socket.close() this.socket.close()
} }
} }
+167 -158
View File
@@ -20,7 +20,7 @@ import { DeleteMessageModel, MessageModel } from '../../models/beast-orm';
import { AESEncrypt } from '../aesencrypt.service'; import { AESEncrypt } from '../aesencrypt.service';
import { IncomingChatMessage, ChatMessageInterface, falseTypingMethod } from 'src/app/models/message.model'; import { IncomingChatMessage, ChatMessageInterface, falseTypingMethod } from 'src/app/models/message.model';
import { AttachmentsService } from 'src/app/services/attachments.service'; 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 { ChatSystemService } from './chat-system.service';
import { ViewedMessageService } from './viewed-message.service' import { ViewedMessageService } from './viewed-message.service'
import * as FIFOProcessQueue from 'fifo-process-queue'; import * as FIFOProcessQueue from 'fifo-process-queue';
@@ -82,8 +82,8 @@ export class RoomService {
return [] return []
} }
sortRoomList = () => {} sortRoomList = () => { }
chatServiceDeleteRoom = (roomId) => {} chatServiceDeleteRoom = (roomId) => { }
constructor( constructor(
public RochetChatConnectorService: RochetChatConnectorService, public RochetChatConnectorService: RochetChatConnectorService,
@@ -136,16 +136,16 @@ export class RoomService {
* @returns * @returns
*/ */
statusNumberToText(text) { statusNumberToText(text) {
if(text == '0') { if (text == '0') {
return "offline" return "offline"
} }
else if(text == '1') { else if (text == '1') {
return "online" return "online"
} }
else if(text == '2') { else if (text == '2') {
return "away" return "away"
} }
else if(text == '3') { else if (text == '3') {
return "busy" 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.customFields = customFields
this.id = id this.id = id
this.name = name this.name = name
@@ -170,16 +171,18 @@ export class RoomService {
this.lastMessage = lastMessage this.lastMessage = lastMessage
this._updatedAt = _updatedAt this._updatedAt = _updatedAt
this.u = u this.u = u
this.members = members
this.membersExcludeMe = membersExcludeMe
this.calDateDuration(); this.calDateDuration();
if(this.customFields?.countDownDate) { if (this.customFields?.countDownDate) {
this.countDownDate(this.customFields.countDownDate); this.countDownDate(this.customFields.countDownDate);
} }
if (this.setDataOnce == false) {
this.setDataOnce = true
this.updateContacts()
}
} }
updateInfo() { updateInfo() {
@@ -189,11 +192,11 @@ export class RoomService {
get online() { get online() {
if(!this.isGroup) { if (!this.isGroup) {
for(let user of this.ChatSystemService.users) { for (let user of this.ChatSystemService.users) {
for (const members of this.membersExcludeMe) { for (const members of this.membersExcludeMe) {
if(members._id == user._id) { if (members._id == user._id) {
return user.status return user.status
} }
} }
@@ -206,14 +209,14 @@ export class RoomService {
countDownDate(date) { countDownDate(date) {
let difference = new Date(date).getTime() - new Date().getTime(); let difference = new Date(date).getTime() - new Date().getTime();
let c_day = Math.floor(difference/(1000*60*60*24)); 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_hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let c_minutes = Math.floor((difference % (1000*60*60)) / (1000*60)); let c_minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
let c_seconds = Math.floor((difference % (1000*60)) / 1000); 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(); this.deleteRoom();
@@ -237,15 +240,15 @@ export class RoomService {
// this.chatService.getRoomInfo(this.id).subscribe( room =>{}); // this.chatService.getRoomInfo(this.id).subscribe( room =>{});
if(this.t === 'p') { if (this.t === 'p') {
this.chatService.deleteGroup(body).subscribe(res=>{ this.chatService.deleteGroup(body).subscribe(res => {
this.ChatSystemService.deleteRoom(this.id); this.ChatSystemService.deleteRoom(this.id);
this.ChatSystemService.getAllRooms(); this.ChatSystemService.getAllRooms();
this.chatServiceDeleteRoom(this.id); this.chatServiceDeleteRoom(this.id);
}); });
} }
else { else {
this.chatService.deleteChannel(body).subscribe(res=>{ this.chatService.deleteChannel(body).subscribe(res => {
this.ChatSystemService.deleteRoom(this.id); this.ChatSystemService.deleteRoom(this.id);
this.ChatSystemService.getAllRooms(); this.ChatSystemService.getAllRooms();
this.chatServiceDeleteRoom(this.id); this.chatServiceDeleteRoom(this.id);
@@ -267,7 +270,7 @@ export class RoomService {
this.RochetChatConnectorService.updateRoomEventss( this.RochetChatConnectorService.updateRoomEventss(
this.id, this.id,
"stream-room-messages", "stream-room-messages",
async (IncomingChatMessage:IncomingChatMessage) => { async (IncomingChatMessage: IncomingChatMessage) => {
this.appendReceiveMessage.push(IncomingChatMessage) this.appendReceiveMessage.push(IncomingChatMessage)
@@ -276,7 +279,7 @@ export class RoomService {
this.RochetChatConnectorService.receiveStreamNotifyRoom((message) => { this.RochetChatConnectorService.receiveStreamNotifyRoom((message) => {
if(message.fields.eventName == this.id+'/'+'typing') { if (message.fields.eventName == this.id + '/' + 'typing') {
const args = message.fields.args const args = message.fields.args
@@ -287,18 +290,18 @@ export class RoomService {
this.otherUserType = args[1] this.otherUserType = args[1]
const user = args[0] const user = args[0]
if(SessionStore.user.UserName != user) { if (SessionStore.user.UserName != user) {
this.readAllMessage() 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] const user = args[0]
if(SessionStore.user.UserName != user) { if (SessionStore.user.UserName != user) {
this.readAllMessage() 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) 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 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) || 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 }) // || await this.findMessageInDBByData({_id:ChatMessage._id, localReference:ChatMessage.localReference })
if(!found) { if (!found) {
ChatMessage.origin = 'stream' ChatMessage.origin = 'stream'
const message = await this.prepareCreate({message: ChatMessage, save: false}); const message = await this.prepareCreate({ message: ChatMessage, save: false });
this.registerSendMessage(message) this.registerSendMessage(message)
message.from = 'stream' message.from = 'stream'
@@ -337,14 +340,14 @@ export class RoomService {
this.name = message.msg; this.name = message.msg;
} }
if(this.isSenderIsNotMe(ChatMessage)) { if (this.isSenderIsNotMe(ChatMessage)) {
/* this.NativeNotificationService.sendNotificationChat({ /* this.NativeNotificationService.sendNotificationChat({
message: message.msg, message: message.msg,
title: this.name title: this.name
}); */ }); */
} }
if(this.hasLoadHistory == true) { if (this.hasLoadHistory == true) {
this.messages.push(message) this.messages.push(message)
await message.addMessageDB() await message.addMessageDB()
} else { } 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() this.updateContacts()
} else if (ChatMessage?.t == "r") { } else if (ChatMessage?.t == "r") {
this.name = ChatMessage.msg this.name = ChatMessage.msg
@@ -374,8 +377,8 @@ export class RoomService {
getUsersByStatus(status: 'offline' | 'online') { getUsersByStatus(status: 'offline' | 'online') {
return this.getAllUsers().filter((user => { return this.getAllUsers().filter((user => {
for(const member of this.membersExcludeMe) { for (const member of this.membersExcludeMe) {
if(user._id == member._id && user.status == status) { if (user._id == member._id && user.status == status) {
return true return true
} }
} }
@@ -385,8 +388,8 @@ export class RoomService {
getRoomMembersIds(): string[] { getRoomMembersIds(): string[] {
try { try {
return this.membersExcludeMe.map((user)=> user._id) return this.membersExcludeMe.map((user) => user._id)
} catch(error) { } catch (error) {
return [] return []
} }
@@ -399,10 +402,10 @@ export class RoomService {
const AllMemberThatIsNotOffline = [] const AllMemberThatIsNotOffline = []
for(let user of allChatUsers) { for (let user of allChatUsers) {
if(membersIds.includes(user._id)) { if (membersIds.includes(user._id)) {
if(user.status != 'offline') { if (user.status != 'offline') {
AllMemberThatIsNotOffline.push(user._id) AllMemberThatIsNotOffline.push(user._id)
} }
} }
@@ -418,10 +421,10 @@ export class RoomService {
const AllMemberThatIsNotOffline = [] const AllMemberThatIsNotOffline = []
for(let user of allChatUsers) { for (let user of allChatUsers) {
if(membersIds.includes(user._id)) { if (membersIds.includes(user._id)) {
if(user.status == 'offline') { if (user.status == 'offline') {
AllMemberThatIsNotOffline.push(user._id) AllMemberThatIsNotOffline.push(user._id)
} }
} }
@@ -433,18 +436,18 @@ export class RoomService {
async deleteMessageToReceive(userId) { 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) message_.needToReceiveBy = message_.needToReceiveBy.filter((e) => e != userId)
this.sendFalseTypingReadMessage('deleteMessage',{_id:message_.messageId}) 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() await deleteMessage.delete()
} else { } else {
@@ -467,13 +470,13 @@ export class RoomService {
const message = this.messages.find((e) => e._id == DeletedMessageId) const message = this.messages.find((e) => e._id == DeletedMessageId)
if(message) { if (message) {
if(message.delate == false) { if (message.delate == false) {
this.deleteMessage(DeletedMessageId) this.deleteMessage(DeletedMessageId)
} }
} else { } else {
const message = await MessageModel.get({_id: DeletedMessageId}) const message = await MessageModel.get({ _id: DeletedMessageId })
if(message) { if (message) {
(message as MessageModel).delete() (message as MessageModel).delete()
DeleteMessageModel.create({ DeleteMessageModel.create({
@@ -500,9 +503,9 @@ export class RoomService {
const id = _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) { if (SessionStore.user.UserName == this.messages[i]?.u?.username) {
@@ -523,8 +526,8 @@ export class RoomService {
//Get previous last message from room //Get previous last message from room
const previousLastMessage = this.messages.slice(-1)[0]; const previousLastMessage = this.messages.slice(-1)[0];
if(previousLastMessage.dateLabel == false) { if (previousLastMessage.dateLabel == false) {
if(previousLastMessage) { if (previousLastMessage) {
this.lastMessage = previousLastMessage; this.lastMessage = previousLastMessage;
this.calDateDuration(previousLastMessage._updatedAt) this.calDateDuration(previousLastMessage._updatedAt)
this.sortRoomList() this.sortRoomList()
@@ -532,7 +535,7 @@ export class RoomService {
} else { } else {
const previousLastMessage = this.messages.slice(-2)[0]; const previousLastMessage = this.messages.slice(-2)[0];
if(previousLastMessage) { if (previousLastMessage) {
this.lastMessage = previousLastMessage; this.lastMessage = previousLastMessage;
this.calDateDuration(previousLastMessage._updatedAt) this.calDateDuration(previousLastMessage._updatedAt)
this.sortRoomList() this.sortRoomList()
@@ -560,9 +563,9 @@ export class RoomService {
const id = _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) this.messages.splice(i, 1)
@@ -578,7 +581,7 @@ export class RoomService {
deleteAll() { deleteAll() {
this.messages.forEach((message) => { this.messages.forEach((message) => {
if(message?._id) { if (message?._id) {
this.sendDeleteRequest(message._id) this.sendDeleteRequest(message._id)
} }
}) })
@@ -588,19 +591,19 @@ export class RoomService {
const deleteMessage = await DeleteMessageModel.all(); 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) { async sendDeleteRequest(msgId) {
const message = this.messages.find((e)=>e._id == msgId) const message = this.messages.find((e) => e._id == msgId)
await message.delateStatusFalse() 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 message.delateRequest = true
await message.saveChanges(); await message.saveChanges();
this.deleteMessage(msgId); this.deleteMessage(msgId);
@@ -609,7 +612,7 @@ export class RoomService {
} else { } else {
this.RochetChatConnectorService.registerCallback({ this.RochetChatConnectorService.registerCallback({
type: 'reConnect', type: 'reConnect',
funx: async ()=> { funx: async () => {
this.sendDeleteRequest(msgId) this.sendDeleteRequest(msgId)
return true return true
@@ -623,11 +626,11 @@ export class RoomService {
/** /**
* @description sen text message * @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({}) this.send({})
} }
@@ -647,14 +650,14 @@ export class RoomService {
//console.log('offlineChatMessage', offlineChatMessage) //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) this.registerSendMessage(message)
if(this.hasLoadHistory == true) { if (this.hasLoadHistory == true) {
await message.addMessageDB() await message.addMessageDB()
} }
@@ -686,27 +689,27 @@ export class RoomService {
localReferenceExist(message: MessageService) { localReferenceExist(message: MessageService) {
for( const localReference of this.messagesLocalReference) { for (const localReference of this.messagesLocalReference) {
if(localReference == message?.localReference) { if (localReference == message?.localReference) {
return true return true
} }
} }
return false 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() this.lastTimeType = new Date().getTime()
const lastIsTyping = this.isTyping const lastIsTyping = this.isTyping
if(text.length >= 1) { if (text.length >= 1) {
this.isTyping = true this.isTyping = true
} else { } else {
this.isTyping = false 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)); 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() this.typingWatch()
} }
sendFalseTypingReadMessage(method,param: object) { 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.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', { method: method, params: param } as falseTypingMethod).catch((error) => console.error(error))
this.setTypingOff() this.setTypingOff()
} }
@@ -723,9 +726,9 @@ export class RoomService {
setTimeout(() => { setTimeout(() => {
const now = new Date().getTime() 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.isTyping = false
this.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', this.isTyping).catch((error) => console.error(error)) 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[] { sortArrayISODate(messages: any): any[] {
return messages.sort((a,b) => return messages.sort((a, b) =>
new Date(b._updatedAt ).getTime() new Date(b._updatedAt).getTime()
- -
new Date(a._updatedAt).getTime()) new Date(a._updatedAt).getTime())
} }
@@ -789,16 +792,16 @@ export class RoomService {
goshPush(ChatMessage) { goshPush(ChatMessage) {
let currentDateMessage = new Date(ChatMessage._updatedAt).toLocaleDateString() let currentDateMessage = new Date(ChatMessage._updatedAt).toLocaleDateString()
if(currentDateMessage) { if (currentDateMessage) {
if(!this.labelDates.find( e => e == currentDateMessage)) { if (!this.labelDates.find(e => e == currentDateMessage)) {
this.labelDates.push(currentDateMessage) this.labelDates.push(currentDateMessage)
const newMessage = this.fix_updatedAt({...ChatMessage}) const newMessage = this.fix_updatedAt({ ...ChatMessage })
newMessage.msg = currentDateMessage newMessage.msg = currentDateMessage
const cloneMessage = new MessageServiceDateLabel() const cloneMessage = new MessageServiceDateLabel()
cloneMessage.ChatSystemService = this.ChatSystemService cloneMessage.ChatSystemService = this.ChatSystemService
cloneMessage.setData({...newMessage} as any) cloneMessage.setData({ ...newMessage } as any)
// //
cloneMessage._id = "" cloneMessage._id = ""
cloneMessage._updatedAt = "" cloneMessage._updatedAt = ""
@@ -809,7 +812,7 @@ export class RoomService {
cloneMessage.file = undefined cloneMessage.file = undefined
cloneMessage.attachments = undefined cloneMessage.attachments = undefined
if(new Date().toLocaleDateString() == currentDateMessage) { if (new Date().toLocaleDateString() == currentDateMessage) {
cloneMessage.msg = "hoje" cloneMessage.msg = "hoje"
} else { } else {
@@ -827,18 +830,18 @@ export class RoomService {
let currentDateMessageToDelete = new Date(MessageService._updatedAt).toLocaleDateString() 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() let currentDateMessage = new Date(this.messages[i]._updatedAt).toLocaleDateString()
if(currentDateMessageToDelete == currentDateMessage) { if (currentDateMessageToDelete == currentDateMessage) {
return return
} }
} }
for (let i =0; i <= this.messages.length; i++) { for (let i = 0; i <= this.messages.length; i++) {
if(this.messages[i].dateLabel) { if (this.messages[i].dateLabel) {
if(this.messages[i].msg == currentDateMessageToDelete) { if (this.messages[i].msg == currentDateMessageToDelete) {
this.messages.splice(i, 1) this.messages.splice(i, 1)
} }
} }
@@ -849,14 +852,14 @@ export class RoomService {
hojeLabel(offlineChatMessage: any) { hojeLabel(offlineChatMessage: any) {
let currentDateMessage = new Date().toLocaleDateString() let currentDateMessage = new Date().toLocaleDateString()
if(!this.labelDates.find( e => e == currentDateMessage)) { if (!this.labelDates.find(e => e == currentDateMessage)) {
this.labelDates.push(currentDateMessage) this.labelDates.push(currentDateMessage)
const cloneMessage = new MessageServiceDateLabel() const cloneMessage = new MessageServiceDateLabel()
cloneMessage.ChatSystemService = this.ChatSystemService cloneMessage.ChatSystemService = this.ChatSystemService
cloneMessage.setData({...offlineChatMessage} as any) cloneMessage.setData({ ...offlineChatMessage } as any)
cloneMessage.msg = "hoje" cloneMessage.msg = "hoje"
cloneMessage._id = "" cloneMessage._id = ""
@@ -872,10 +875,10 @@ export class RoomService {
} }
async restoreMessageFromDB() { async restoreMessageFromDB() {
if(environment.chatOffline && this.restoreOnce == false) { if (environment.chatOffline && this.restoreOnce == false) {
this.restoreOnce = true 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) {
@@ -889,9 +892,9 @@ export class RoomService {
wewMessage.loadHistory = this.hasLoadHistory wewMessage.loadHistory = this.hasLoadHistory
wewMessage.messageModelInstance = ChatMessage 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' message.from = 'Offline'
@@ -901,7 +904,7 @@ export class RoomService {
} else { } else {
const offlineMessage = await this.prepareCreate({message:ChatMessage}) const offlineMessage = await this.prepareCreate({ message: ChatMessage })
offlineMessage.from = 'Offline' offlineMessage.from = 'Offline'
offlineMessage.loadHistory = this.hasLoadHistory 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) this.sendDeleteRequest(wewMessage._id)
} }
} }
if(!this.lastMessage) { if (!this.lastMessage) {
this.lastMessage = messages.pop(); this.lastMessage = messages.pop();
} }
@@ -931,9 +934,9 @@ export class RoomService {
// runs onces only // runs onces only
loadHistoryCount = 0 loadHistoryCount = 0
localMessages = [] localMessages = []
async loadHistory({limit = 1000, forceUpdate = false }) { async loadHistory({ limit = 1000, forceUpdate = false }) {
if(forceUpdate == false) { if (forceUpdate == false) {
if (this.hasLoadHistory) { if (this.hasLoadHistory) {
return false return false
} }
@@ -944,18 +947,18 @@ export class RoomService {
await this.restoreMessageFromDB() await this.restoreMessageFromDB()
const chatHistory: chatHistory = await this.RochetChatConnectorService.loadHistory(this.id, limit) 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') 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.origin = 'history'
message.from = 'History' message.from = 'History'
const messagesToSave = await this.prepareMessageCreateIfNotExist({message: message}); const messagesToSave = await this.prepareMessageCreateIfNotExist({ message: message });
if(messagesToSave != null) { if (messagesToSave != null) {
messagesToSave.received = users.map((user) => user._id) messagesToSave.received = users.map((user) => user._id)
messagesToSave.addMessageDB() messagesToSave.addMessageDB()
@@ -964,9 +967,9 @@ export class RoomService {
} }
for( const message of this.messagesBeforeOfflineAPI) { for (const message of this.messagesBeforeOfflineAPI) {
const messagesToSave = await this.prepareMessageCreateIfNotExist({message: message}); const messagesToSave = await this.prepareMessageCreateIfNotExist({ message: message });
if(messagesToSave != null) { if (messagesToSave != null) {
messagesToSave.received = users.map((user) => user._id) messagesToSave.received = users.map((user) => user._id)
@@ -983,9 +986,9 @@ export class RoomService {
this.DoneLoadingHistory = true 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 this.lastMessage = chatHistory?.result?.messages.pop() as any
} }
} }
@@ -996,11 +999,11 @@ export class RoomService {
deletedMessages(chatHistory: chatHistory) { deletedMessages(chatHistory: chatHistory) {
const messagesToDelete = this.localMessages.filter( id => { const messagesToDelete = this.localMessages.filter(id => {
const found = chatHistory.result.messages.find( e => { const found = chatHistory.result.messages.find(e => {
return e._id == id return e._id == id
}) })
if(!found) { if (!found) {
return true return true
} }
@@ -1009,13 +1012,13 @@ export class RoomService {
for (const id of messagesToDelete) { for (const id of messagesToDelete) {
if(id != '') { if (id != '') {
this.deleteMessage(id) this.deleteMessage(id)
} }
} }
} }
addMessageDB = FIFOProcessQueue(async ({messagesToSave}, callback) => { addMessageDB = FIFOProcessQueue(async ({ messagesToSave }, callback) => {
await messagesToSave.addMessageDB() await messagesToSave.addMessageDB()
callback() callback()
@@ -1029,7 +1032,7 @@ export class RoomService {
async ChatMessageIsPresentInTheView(ChatMessage:ChatMessageInterface) { async ChatMessageIsPresentInTheView(ChatMessage: ChatMessageInterface) {
let foundIndex; let foundIndex;
const found = this.messages.find((MessageService, index) => { const found = this.messages.find((MessageService, index) => {
@@ -1042,7 +1045,7 @@ export class RoomService {
}) })
if (foundIndex) { if (foundIndex) {
return { found, foundIndex} return { found, foundIndex }
} else { } else {
return false return false
} }
@@ -1051,14 +1054,14 @@ export class RoomService {
async prepareCreate({message, save = true}): Promise<MessageService> { async prepareCreate({ message, save = true }): Promise<MessageService> {
message = this.fix_updatedAt(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.setData(message)
wewMessage.loadHistory = this.hasLoadHistory wewMessage.loadHistory = this.hasLoadHistory
if(save) { if (save) {
this.messages.push(wewMessage) this.messages.push(wewMessage)
} }
@@ -1068,7 +1071,7 @@ export class RoomService {
simplePrepareMessage(message) { simplePrepareMessage(message) {
message = this.fix_updatedAt(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.setData(message)
wewMessage.loadHistory = this.hasLoadHistory wewMessage.loadHistory = this.hasLoadHistory
@@ -1076,9 +1079,9 @@ export class RoomService {
} }
private findMessageBy_id (id) { private findMessageBy_id(id) {
for( let m of this.messages) { for (let m of this.messages) {
if(m?._id == id) { if (m?._id == id) {
return true return true
} }
} }
@@ -1086,9 +1089,9 @@ export class RoomService {
return false return false
} }
private findMessageBy_localReference (localReference) { private findMessageBy_localReference(localReference) {
for( let m of this.messages) { for (let m of this.messages) {
if(m?.localReference == localReference) { if (m?.localReference == localReference) {
return true return true
} }
} }
@@ -1096,27 +1099,27 @@ export class RoomService {
return false return false
} }
private async findMessageInDBByLocalReference({localReference}) { private async findMessageInDBByLocalReference({ localReference }) {
const a = await MessageModel.get({localReference: localReference}) const a = await MessageModel.get({ localReference: localReference })
return typeof a.id == 'number' return typeof a.id == 'number'
} }
private async findMessageInDBByLocalId({_id}) { private async findMessageInDBByLocalId({ _id }) {
const a = await MessageModel.get({_id: _id}) const a = await MessageModel.get({ _id: _id })
return typeof a.id == 'number' return typeof a.id == 'number'
} }
private async findMessageInDBByData({localReference, _id}) { private async findMessageInDBByData({ localReference, _id }) {
const a = await MessageModel.filter({localReference: localReference}).execute() const a = await MessageModel.filter({ localReference: localReference }).execute()
if(a.length >= 1) { if (a.length >= 1) {
return true return true
} }
const c = await MessageModel.filter({_id: _id}).execute() const c = await MessageModel.filter({ _id: _id }).execute()
if(c.length >= 1) { if (c.length >= 1) {
return true return true
} }
@@ -1125,7 +1128,7 @@ export class RoomService {
return false return false
} }
async prepareMessageCreateIfNotExist({message}) { async prepareMessageCreateIfNotExist({ message }) {
message = this.fix_updatedAt(message) message = this.fix_updatedAt(message)
let found = await this.findMessageBy_id(message._id) || await this.findMessageBy_localReference(message.localReference) let found = await this.findMessageBy_id(message._id) || await this.findMessageBy_localReference(message.localReference)
@@ -1149,8 +1152,8 @@ export class RoomService {
private fix_updatedAt(message): ChatMessageInterface { private fix_updatedAt(message): ChatMessageInterface {
if (message?.result) { if (message?.result) {
message.result._updatedAt = message.result._updatedAt['$date'] message.result._updatedAt = message.result._updatedAt['$date']
} else if(message?._updatedAt) { } else if (message?._updatedAt) {
if(message._updatedAt.hasOwnProperty('$date')) { if (message._updatedAt.hasOwnProperty('$date')) {
message._updatedAt = message._updatedAt['$date'] message._updatedAt = message._updatedAt['$date']
} }
} }
@@ -1163,21 +1166,21 @@ export class RoomService {
const firstName = capitalizeTxt(username.split('.')[0]) const firstName = capitalizeTxt(username.split('.')[0])
const lastName = capitalizeTxt(username.split('.')[1]) const lastName = capitalizeTxt(username.split('.')[1])
return firstName + ' ' + lastName return firstName + ' ' + lastName
} catch(error) { } catch (error) {
return username return username
} }
} }
sendReadMessage() { sendReadMessage() {
this.RochetChatConnectorService.readMessage(this.id).catch((error) =>{ this.RochetChatConnectorService.readMessage(this.id).catch((error) => {
console.error(error) console.error(error)
}) })
this.sendFalseTypingReadMessage('viewMessage', {}) this.sendFalseTypingReadMessage('viewMessage', {})
this.messageUnread = false this.messageUnread = false
} }
async addContacts(userId:any) { async addContacts(userId: any) {
let body = { let body = {
"roomId": this.id, "roomId": this.id,
@@ -1194,7 +1197,7 @@ export class RoomService {
let res let res
let error = false let error = false
if(this.t == 'd') { if (this.t == 'd') {
try { try {
res = await this.chatService.getMembers(this.id).toPromise(); res = await this.chatService.getMembers(this.id).toPromise();
@@ -1203,7 +1206,7 @@ export class RoomService {
error = true error = true
} }
if(error) { if (error) {
res = await this.chatService.getMembers(this.id).toPromise(); res = await this.chatService.getMembers(this.id).toPromise();
} }
@@ -1217,11 +1220,14 @@ export class RoomService {
error = true error = true
} }
if(error) { if (error) {
res = await this.chatService.getGroupMembers(this.id).toPromise() res = await this.chatService.getGroupMembers(this.id).toPromise()
} }
setTimeout(() => {
console.log("getGroupMembers", this.membersExcludeMe)
}, 500)
} }
else { else {
@@ -1234,10 +1240,13 @@ export class RoomService {
error = true error = true
} }
if(error) { if (error) {
res = await this.chatService.getChannelMembers(this.id).toPromise() res = await this.chatService.getChannelMembers(this.id).toPromise()
} }
setTimeout(() => {
console.log("getChannelMembers", this.membersExcludeMe)
}, 500)
} }
} }
@@ -367,13 +367,19 @@ export class NotificationsService {
let navigationExtras: NavigationExtras = { queryParams: { "roomId": notification.notification.data.IdObject, } }; let navigationExtras: NavigationExtras = { queryParams: { "roomId": notification.notification.data.IdObject, } };
if (window.location.search.includes("roomId")) {
this.zone.run(() => this.router.navigate(['/home/chat'])); this.zone.run(() => this.router.navigate(['/home/chat']));
}
setTimeout(() => { setTimeout(() => {
this.zone.run(() => this.router.navigate(['/home/chat'], navigationExtras)); this.zone.run(() => this.router.navigate(['/home/chat'], navigationExtras));
}, 200); }, 200);
} }
// (() => {
// this.zone.run(() => this.NotificationHolderService.PhoneClickNotification(notification));
// })()
} }
} }
+62 -24
View File
@@ -1,6 +1,7 @@
import { Injectable, NgZone } from '@angular/core'; import { Injectable, NgZone } from '@angular/core';
import { StorageService } from '../services/storage.service'; import { StorageService } from '../services/storage.service';
import { v4 as uuidv4 } from 'uuid' import { v4 as uuidv4 } from 'uuid'
import { SHA1 } from 'crypto-js';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
@@ -40,17 +41,13 @@ export class NotificationHolderService {
this.storageService.store("Notifications", this._notificationList) this.storageService.store("Notifications", this._notificationList)
} }
addNotification(notification) { notificationObject(notification) {
const element = notification const element = notification
const i = this._notificationList.length + 1
let notificationObject; let notificationObject;
if (element.notification) { if (element.notification) {
notificationObject = { notificationObject = {
id: notification?.id || uuidv4(), id: notification?.id,
index: i,
title: element.notification.title, title: element.notification.title,
Service: element.data.Service, Service: element.data.Service,
Object: element.data.Object, Object: element.data.Object,
@@ -68,8 +65,7 @@ export class NotificationHolderService {
} else if (element.data) { } else if (element.data) {
notificationObject = { notificationObject = {
id: notification?.id || uuidv4(), id: notification?.id,
index: i,
title: element.title, title: element.title,
Service: element.data.Service, Service: element.data.Service,
Object: element.data.Object, Object: element.data.Object,
@@ -88,25 +84,38 @@ export class NotificationHolderService {
} else { } else {
{ {
notificationObject = { notificationObject = {
id: notification?.id || uuidv4(), id: notification?.id,
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,
title: element.title, 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, 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)) { if (!this.notificationExist(notificationObject)) {
this._notificationList.push(notificationObject) this._notificationList.push(notificationObject)
@@ -115,14 +124,11 @@ export class NotificationHolderService {
this.save() this.save()
}) })
} else { } else {
console.log('duplicate', notification, this._notificationList) console.log('duplicate', notification, this._notificationList)
} }
} }
notificationExist(notificationObject) { notificationExist(notificationObject) {
const notification = this._notificationList.find(item => { const notification = this._notificationList.find(item => {
return item.id === notificationObject.id; 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 })
}
//}
}
} }