This commit is contained in:
Peter Maquiran
2022-02-10 20:16:15 +01:00
24 changed files with 400 additions and 257 deletions
+1
View File
@@ -81,6 +81,7 @@ export interface Message {
editedBy: EditedBy;
urls: any[];
temporaryData: object
localReference?: string
}
@@ -60,7 +60,7 @@
<div class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}' *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'au' && msg.t != 'ru' && msg.msg !=''" (press)="handlePress(msg._id)">
<div class="title">
<ion-label>{{msg.u.name ?? ""}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div class="message">
<ion-label>{{msg.msg}}</ion-label>
@@ -75,7 +75,7 @@
</div>
<div class="title">
<ion-label>{{msg.u.name ?? ""}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div>
<ion-label>{{msg.msg}}</ion-label>
@@ -96,7 +96,7 @@
<div class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}' class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}' *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'ru' && msg.file.type != 'application/meeting'" (press)="handlePress(msg._id)">
<div class="title">
<ion-label>{{msg.u.name ?? ""}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div class="message">
<div *ngIf="msg.attachments" class="message-attachments">
@@ -196,7 +196,7 @@
</div>
<div class="message-box width-80">
<ion-item class="ion-no-padding type-message" lines="none">
<ion-textarea autocomplete="on" autocorrect="on" spellcheck="true" clearOnEdit="true" placeholder="Escrever uma mensagem" auto-grow class="message-input" rows="1" [(ngModel)]="wsChatMethodsService.getGroupRoom(roomId).message" (ionChange)="changeInput()"></ion-textarea>
<ion-textarea autocomplete="on" autocorrect="on" spellcheck="true" clearOnEdit="true" placeholder="Escrever uma mensagem" auto-grow class="message-input" rows="1" [(ngModel)]="wsChatMethodsService.getGroupRoom(roomId).message" (ionChange)="wsChatMethodsService.getGroupRoom(roomId).sendTyping()"></ion-textarea>
<button hidden class="btn-no-color">
<ion-icon slot="end" src="assets/icon/icons-chat-mic.svg"></ion-icon>
</button>
@@ -109,7 +109,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
};
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory();
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory({});
this.wsChatMethodsService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked;
this.wsChatMethodsService.openRoom(this.roomId)
@@ -198,10 +198,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
changeInput() {
this.wsChatMethodsService.getGroupRoom(this.roomId).typing()
}
async goToEvent(eventId: any) {
let classs;
if (window.innerWidth < 701) {
@@ -490,7 +486,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
const data = res.data;
if(data.selected) {
const loader = this.toastService.loading();
this.wsChatMethodsService.getGroupRoom(this.roomId).send({
file:{
@@ -514,9 +509,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}]
})
loader.remove();
}
});
}
@@ -53,7 +53,7 @@
<div (press)="handlePress(msg._id)" class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}' (click)="downloadFileMsg(msg)" *ngIf="msg.msg !=''">
<div class="title">
<ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div>
<ion-label>{{msg.msg}}</ion-label>
@@ -64,7 +64,7 @@
<!-- <div (press)="handlePress(msg._id)" class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}' (click)="openPreview(msg)" *ngIf="msg.msg !=''">
<div class="title">
<ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div>
<ion-label>{{msg.msg}}</ion-label>
@@ -77,7 +77,7 @@
<div (press)="handlePress(msg._id)" class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}' *ngIf="msg.file.type != 'application/meeting'">
<div class="title">
<ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div>
<div *ngIf="msg.attachments" class="message-attachments">
@@ -186,7 +186,7 @@
</div>
<div class="width-70">
<ion-item class="ion-no-padding ion-no-margin type-message" lines="none">
<ion-textarea autocomplete="on" autocorrect="on" spellcheck="true" *ngIf="!recording" clearOnEdit="true" placeholder="Escrever uma mensagem" auto-grow class="message-input" rows="1" [(ngModel)]="wsChatMethodsService.getDmRoom(roomId).message" (ionChange)="changeInput()"></ion-textarea>
<ion-textarea autocomplete="on" autocorrect="on" spellcheck="true" *ngIf="!recording" clearOnEdit="true" placeholder="Escrever uma mensagem" auto-grow class="message-input" rows="1" [(ngModel)]="wsChatMethodsService.getDmRoom(roomId).message" (ionChange)="wsChatMethodsService.getDmRoom(roomId).sendTyping()"></ion-textarea>
<ion-textarea autocomplete="on" spellcheck="true" *ngIf="recording" clearOnEdit="true" placeholder="Escrever uma mensagem" auto-grow class="message-input" rows="1" [(ngModel)]="durationDisplay"></ion-textarea>
<button hidden #recordbtn class="btn-no-color" (click)="notImplemented()">
<ion-icon slot="end" src="assets/icon/icons-chat-mic.svg"></ion-icon>
+1 -7
View File
@@ -124,7 +124,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
};
this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory()
this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory({})
this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked
this.wsChatMethodsService.openRoom(this.roomId)
@@ -348,16 +348,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
window.removeEventListener('scroll', this.scrollChangeCallback, true);
}
changeInput() {
this.wsChatMethodsService.getDmRoom(this.roomId).typing()
}
sendMessage() {
this.wsChatMethodsService.getDmRoom(this.roomId).send({})
}
viewDocument(file: any, url?: string) {
if (file.type == "application/webtrix") {
@@ -16,7 +16,7 @@
<ion-toolbar>
<ion-segment [(ngModel)]="segment" (ionChange)="segmentChanged($event)">
<ion-segment-button value="MDGPR">
Calendário do MDGPR
Calendário MDGPR
</ion-segment-button>
<ion-segment-button value="PR">
Presidente da República
+2
View File
@@ -103,6 +103,7 @@ export class LoginPage implements OnInit {
if (attempt.UserId == SessionStore.user.UserId) {
await this.authService.SetSession(attempt, this.userattempt);
await this.authService.loginChat();
await this.authService.loginToChatWs()
this.getToken();
SessionStore.setInativity(true);
@@ -117,6 +118,7 @@ export class LoginPage implements OnInit {
this.changeProfileService.run()
await this.authService.loginChat();
await this.authService.loginToChatWs()
this.getToken();
this.router.navigateByUrl('/pin', { replaceUrl: true });
}
+4 -2
View File
@@ -43,7 +43,6 @@ export class AlertService {
}
async confirmDeleteMessage(msgId:any, room:any) {
console.log(room);
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
@@ -60,7 +59,10 @@ export class AlertService {
text: 'Apagar',
handler: () => {
//const loader = this.toastService.loading();
this.wsChatMethodsService.deleteMessage(msgId);
this.wsChatMethodsService.deleteMessage(msgId).then(()=>{
room.deleteMessage(msgId)
})
//this.wsChatMethodsService.subscribeToRoomUpdate(room._id, room);
//loader.remove();
}
+9 -10
View File
@@ -112,7 +112,7 @@ export class AuthService {
//user: UserForm
async loginChat() {
const expirationMinutes = 60;
const expirationMinutes = 30;
let date = new Date().getTime();
let expirationDate = new Date(new Date().getTime() + expirationMinutes*60*1000);
@@ -125,8 +125,6 @@ export class AuthService {
if(responseChat) {
this.loginToChatWs()
console.log('Login to Rocket chat OK', responseChat);
this.ValidatedUserChat = responseChat;
localStorage.setItem('userChat', JSON.stringify(responseChat));
@@ -146,7 +144,7 @@ export class AuthService {
}, expirationDate)
}
private loginToChatWs() {
loginToChatWs() {
setTimeout(()=>{
this.WsChatService.connect();
@@ -167,6 +165,7 @@ export class AuthService {
try {
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
message.file.guid = guid.path
alert('uploaded')
await this.storage.set(guid.path, message.file.image_url).then(() => {
console.log('add picture to chat IMAGE SAVED')
message.getFileFromDb()
@@ -199,7 +198,7 @@ export class AuthService {
}
this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => {
this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => {
console.log('FILE TYPE', message.file.type)
let downloadFile = "";
@@ -207,20 +206,20 @@ export class AuthService {
const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise();
console.log('FILE TYPE 22', message.file.guid)
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
console.log('FILE TYPE 33', message.file.type)
return true
} else if (event.type === HttpEventType.Response) {
downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
message.file = {
guid: message.file.guid,
image_url: downloadFile,
type: message.file.type
}
await this.storage.set(message.file.guid, downloadFile).then(() => {
console.log('IMAGE SAVED')
});
@@ -228,10 +227,10 @@ export class AuthService {
}
return false
}
};
}, 1)
+56 -25
View File
@@ -5,6 +5,8 @@ import { SessionStore } from 'src/app/store/session.service';
import { capitalizeTxt } from 'src/plugin/text'
import { NfService } from 'src/app/services/chat/nf.service'
import { WsChatService } from 'src/app/services/chat/ws-chat.service';
import { environment } from 'src/environments/environment';
import { showDateDuration } from 'src/plugin/showDateDuration';
@Injectable({
providedIn: 'root'
})
@@ -30,14 +32,17 @@ export class MessageService {
sendAttempt = 0
uploadingFile = false
errorUploadingAttachment = false
loadHistory = false
duration = ''
localReference = null
constructor(private storage: Storage,
private NfService: NfService,
private WsChatService: WsChatService) {
}
setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData}:Message) {
this.customFields = customFields
setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData, localReference}:Message) {
this.customFields = customFields
this.channels = channels || []
this.mentions = mentions || []
this.msg = msg || ""
@@ -50,6 +55,7 @@ export class MessageService {
this.file = file
this.attachments = attachments
this.temporaryData = temporaryData
this.localReference = localReference || null
if(!this.ts) {
this.offline = true
@@ -71,6 +77,8 @@ export class MessageService {
this.displayType = this.file.type.replace('application/','').toUpperCase()
}
}
this.calDateDuration()
}
private usernameToDisplayName(username) {
@@ -78,7 +86,7 @@ export class MessageService {
const firstName = capitalizeTxt(username.split('.')[0])
const lastName = capitalizeTxt(username.split('.')[1])
return firstName + ' ' + lastName
}
}
getFileFromDb() {
@@ -93,19 +101,26 @@ export class MessageService {
}
}
async send() {
async send(): Promise<any> {
this.sendAttempt++;
if(!this.hasFile) {
console.log('simple send')
this.WsChatService.send({roomId:this.rid, msg:this.msg}).then((data: any) => {
let ChatMessage = data.result
this.redefinedMessage(this, ChatMessage)
this.offline = false
this.WsChatService.send({roomId:this.rid, msg:this.msg, requestId: this.localReference}).then(({message, requestId}) => {
let ChatMessage = message.result
if (environment.chatOffline) {
this.redefinedMessage(ChatMessage)
alert('redifie')
this.offline = false
}
return new Promise((resolve, reject)=>{
resolve(ChatMessage)
})
})
} else {
console.log('complex send')
this.uploadingFile = true
@@ -113,41 +128,52 @@ export class MessageService {
if(this.hasSendAttachment == false) {
uploadSuccessfully = await this.NfService.beforeSendAttachment(this)
}
this.uploadingFile = false
if(uploadSuccessfully || this.hasSendAttachment == false) {
this.hasSendAttachment = true
this.errorUploadingAttachment = false
this.temporaryData = {}
this.WsChatService.send({roomId:this.rid, msg: this.msg, attachments: this.attachments, file: this.file}).then((data: any) => {
console.log('send sucees', data.result)
let ChatMessage = data.result
this.redefinedMessage(this, ChatMessage)
this.offline = false
alert('to send')
this.WsChatService.send({roomId:this.rid, msg: this.msg, attachments: this.attachments, file: this.file, requestId: this.localReference}).then(({message, requestId}) => {
alert('receive11')
console.log('message', message)
let ChatMessage = message.result
if (environment.chatOffline) {
this.redefinedMessage(ChatMessage)
this.offline = false
}
return new Promise((resolve, reject)=>{
resolve(ChatMessage)
})
})
} else if(this.WsChatService.isLogin == false) {
this.WsChatService.registerCallback({
type: 'reConnect',
funx:()=> {
alert('reConnect')
// this.send()
return true
funx: async ()=> {
return await this.send()
}
})
} else if(uploadSuccessfully == false) {
this.errorUploadingAttachment = true
return new Promise((resolve, reject)=>{
reject(false)
})
}
}
}
redefinedMessage(messagem, ChatMessage) {
redefinedMessage(ChatMessage) {
ChatMessage = this.NfService.fix_updatedAt(ChatMessage)
this.setData(ChatMessage)
}
@@ -160,4 +186,9 @@ export class MessageService {
}
private calDateDuration(date = null) {
this.duration = showDateDuration(date || this._updatedAt);
}
}
+13 -2
View File
@@ -7,8 +7,19 @@ import { RoomService } from './room.service';
})
export class NfService {
beforeSendAttachment = async (message: MessageService, room?: RoomService): Promise<boolean> => new Promise ((resolve, reject)=> (resolve(true)))
downloadFileMsg = async (message: MessageService, room?: RoomService): Promise<boolean> => new Promise ((resolve, reject)=> (resolve(true)))
beforeSendAttachment = async (message: MessageService, room?: RoomService): Promise<boolean> => new Promise ((resolve, reject)=> (resolve(true)));
downloadFileMsg = async (message: MessageService, room?: RoomService): Promise<boolean> => new Promise ((resolve, reject)=> (resolve(true)));
fix_updatedAt(message) {
if (message.result) {
message.result._updatedAt = message.result._updatedAt['$date']
} else if(message._updatedAt) {
if(message._updatedAt.hasOwnProperty('$date')) {
message._updatedAt = message._updatedAt['$date']
}
}
return message
}
constructor() { }
}
+188 -109
View File
@@ -14,8 +14,9 @@ import { SortService } from '../functions/sort.service';
import { chatUser } from 'src/app/models/chatMethod';
import { environment } from 'src/environments/environment';
import { ChatService } from 'src/app/services/chat.service';
import { NfService } from 'src/app/services/chat/nf.service'
import alasql from 'alasql'
import { NfService } from 'src/app/services/chat/nf.service';
import { v4 as uuidv4 } from 'uuid'
@Injectable({
providedIn: 'root'
})
@@ -24,13 +25,13 @@ export class RoomService {
messages: MessageService[] = []
storageMessage: any[] = [];
lastMessage: MessageService;
customFields: any;
id = ''
t = ''
name = ''
_updatedAt = {}
private hasLoadHistory = false
hasLoadHistory = false
duration = ''
isTyping = false
otherUserType = false
@@ -38,10 +39,11 @@ export class RoomService {
message = ''
lastMessageTxt = ''
userThatIsTyping = ''
private ToastService = ToastsService
mgsArray = [];
messagesLocalReference = []
scrollDown = () => { }
/**
@@ -90,40 +92,35 @@ export class RoomService {
this.WsChatService.updateRoomEventss(
this.id,
"stream-room-messages",
(ChatMessage) => {
setTimeout(() => {
ChatMessage = ChatMessage.fields.args[0]
(_ChatMessage) => {
console.log('recivemessage', _ChatMessage)
alert('receive')
setTimeout(()=>{
let ChatMessage = _ChatMessage.fields.args[0]
ChatMessage = this.fix_updatedAt(ChatMessage)
// console.log('recivemessage', ChatMessage)
const message = this.prepareMessage(ChatMessage)
this.lastMessage = message
this.calDateDuration(ChatMessage._updatedAt)
const messageIsFound = this.messages.find((message) => {
return message._id == ChatMessage._id
})
if (message.t == 'r') {
this.name = message.msg
}
if(!messageIsFound) {
const message = this.prepareMessage(ChatMessage)
this.lastMessage = message
if (message.t == 'r') { this.name = message.msg }
this.calDateDuration(ChatMessage._updatedAt)
setTimeout(() => {
this.scrollDown()
}, 100)
if(this.isSenderIsNotMe(ChatMessage)) {
this.NativeNotificationService.sendNotificationChat({
message: message.msg,
title: this.name
});
if(this.isSenderIsNotMe(ChatMessage)) {
//this.addMessageDB(ChatMessage)
}
}
this.addMessageDB(ChatMessage)
setTimeout(()=>{
this.scrollDown()
}, 50)
}, 150)
}
@@ -136,6 +133,7 @@ export class RoomService {
if(message.fields.eventName == this.id+'/'+'typing') {
this.userThatIsTyping = this.usernameToDisplayName(message.fields.args[0])
console.log(this.userThatIsTyping, 'this.userThatIsTyping')
this.isTyping = message.fields.args[1]
this.otherUserType = message.fields.args[1]
@@ -144,17 +142,90 @@ export class RoomService {
})
}
async addMessageDB(ChatMessage) {
if (environment.chatOffline) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
/* addMessageDB(ChatMessage) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(messages==null) messages = []
delete ChatMessage.temporaryData
messages.push(ChatMessage)
if(!ChatMessage._id && environment.chatOffline) {
this.storage.set('chatmsg' + this.id, messages)
})
} */
delete ChatMessage.temporaryData
messages.push(ChatMessage)
this.storage.set('chatmsg' + this.id, messages)
} else {
const find = messages.find((message)=> {
return message._id == ChatMessage._id
})
if(!find) {
delete ChatMessage.temporaryData
messages.push(ChatMessage)
this.storage.set('chatmsg' + this.id, messages)
}
}
})
}
}
async updateMessageDB(ChatMessage, localReference) {
if (environment.chatOffline) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
let index;
const find = messages.find((message, _index)=> {
if(message.localReference) {
if(message.localReference == ChatMessage.localReference) {
index = _index
return true
}
}
return false
})
if(find) {
messages[index] = ChatMessage
this.storage.set('chatmsg' + this.id, messages)
}
})
}
}
/**
* @description delete message in the DB. get all messages, delete then corresponding message and update the store
* @param id message ID
*/
private deleteMessageFromDb(id) {
if (environment.chatOffline) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(!Array.isArray(messages)) {
messages = []
}
messages.forEach((message, index) => {
if(message._id == id) {
messages.splice(index, 1)
}
})
this.storage.set('chatmsg' + this.id, messages).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
});
})
}
}
async receiveMessageDelete() {
@@ -193,58 +264,47 @@ export class RoomService {
}
/**
* @description delete message in the DB. get all messages, delete then corresponding message and update the store
* @param id message ID
*/
private deleteMessageFromDb(id) {
this.storage.get('chatmsg' + this.id).then((messages: any = []) => {
if(messages==null) messages = []
messages.forEach((message, index) => {
if(message._id == id) {
messages.splice(index, 1)
}
})
this.storage.set('chatmsg' + this.id, messages).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
});
})
}
/**
* @description sen text message
*/
async send({file = null, attachments = null, temporaryData = {}}) {
const localReference = uuidv4() + 'peter'
let offlineChatMessage = {
rid: this.id,
msg: this.message,
attachments,
file,
temporaryData
temporaryData,
localReference
}
console.log('offlineChatMessage', offlineChatMessage)
const message: MessageService = this.prepareMessage(offlineChatMessage, environment.chatOffline)
//this.addMessageDB(offlineChatMessage)
const message: MessageService = this.prepareMessage(offlineChatMessage)
setTimeout(() => {
this.scrollDown()
}, 150)
this.lastMessage = message
message.send().then((ChatMessage) => {
this.updateMessageDB(ChatMessage, localReference)
})
message.send()
this.calDateDuration(message._updatedAt)
this.sortRoomList()
if (environment.chatOffline) {
this.messagesLocalReference.push(localReference)
this.addMessageDB(offlineChatMessage)
setTimeout(() => {
this.scrollDown()
}, 150)
this.lastMessage = message
this.calDateDuration(message._updatedAt)
this.sortRoomList()
}
this.message= ''
}
@@ -262,7 +322,7 @@ export class RoomService {
}
typing(text:string = this.message) {
sendTyping(text:string = this.message) {
if(this.lastMessageTxt == text) { return false }
this.lastTimeType = new Date().getTime()
@@ -302,7 +362,7 @@ export class RoomService {
}
private setTypingOff() {
this.typing('')
this.sendTyping('')
}
roomLeave() {
@@ -329,48 +389,59 @@ export class RoomService {
async restoreMessageFromDB() {
await this.storage.get('chatmsg' + this.id).then( async (messages = []) => {
if(messages==null) messages = []
if(environment.chatOffline) {
await messages.forEach( async (ChatMessage, index) => {
const wewMessage = this.prepareMessage(ChatMessage, false)
if(wewMessage.offline == false) {
this.prepareMessage(ChatMessage)
await this.storage.get('chatmsg' + this.id).then( async (messages = []) => {
if(!Array.isArray(messages)) {
messages = []
}
});
await messages.forEach( async (ChatMessage, index) => {
const wewMessage = this.prepareMessage(ChatMessage, false)
setTimeout(()=> {
this.scrollDown()
}, 50)
})
if(wewMessage.offline == false) {
this.prepareMessage(ChatMessage)
} else {
if(environment.chatOffline) alert('create offline')
const offlineMessage = this.prepareMessage(ChatMessage)
offlineMessage.send().then(()=>{
this.updateMessageDB(ChatMessage, ChatMessage.localReference)
})
}
});
setTimeout(()=> {
this.scrollDown()
}, 50)
})
}
}
// runs onces only
async loadHistory(limit = 100) {
async loadHistory({limit = 50, forceUpdate = false }) {
if (this.hasLoadHistory) { return false }
this.restoreMessageFromDB()
if(forceUpdate == false) {
if (this.hasLoadHistory) {
return false
}
}
await this.restoreMessageFromDB()
await this.WsChatService.loadHistory(this.id, limit).then( async (chatHistory:chatHistory) => {
console.log('loadHistory', chatHistory)
this.messages = []
await chatHistory.result.messages.reverse().forEach( async (message) => {
this.prepareMessage(message)
this.messages = this.sortService.sortDate(this.messages, '_updatedAt')
const wewMessage = this.prepareMessage(message, false)
})
if(wewMessage.offline == false) {
this.prepareMessage(message)
}
});
this.storage.set('chatmsg' + this.id, chatHistory)
this.storage.set('chatmsg' + this.id, chatHistory.result.messages)
})
setTimeout(() => {
@@ -386,22 +457,32 @@ export class RoomService {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService)
wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory
if (save) {
if(!message._id && environment.chatOffline) {
if(this.hasLoadHistory && environment.chatOffline) alert('create offline')
this.messages.push(wewMessage)
return wewMessage
}
const found = this.messages.find((MessageService) => {
if (MessageService._id == message._id) {
if(this.hasLoadHistory) console.log(`${MessageService._id} == ${message._id}`)
return true
} else {
return false
}
})
if (save && !found) {
if(this.hasLoadHistory && environment.chatOffline) alert('not found')
this.messages.push(wewMessage)
}
return wewMessage
}
async returnData(res) {
return res;
}
ReactToMessage() { }
private calDateDuration(date = null) {
this.duration = showDateDuration(date || this._updatedAt);
this._updatedAt = date || this._updatedAt
@@ -410,11 +491,9 @@ export class RoomService {
private fix_updatedAt(message) {
if (message.result) {
//console.log('FIX UPDATE ', message.result)
message.result._updatedAt = message.result._updatedAt['$date']
} else if(message._updatedAt) {
if(message._updatedAt.hasOwnProperty('$date')) {
// console.log('FIX UPDATE 11', message)
message._updatedAt = message._updatedAt['$date']
}
}
@@ -13,15 +13,14 @@ import { NativeNotificationService } from 'src/app/services/native-notification.
import { SortService } from '../functions/sort.service';
import { chatUser } from 'src/app/models/chatMethod';
import { NfService } from 'src/app/services/chat/nf.service'
import { ChangeProfileService } from '../change-profile.service';
@Injectable({
providedIn: 'root'
})
export class WsChatMethodsService {
dm = {}
group = {}
dm: {[key: string]: RoomService} = {}
group: {[key: string]: RoomService} = {}
_dm = []
_group = []
@@ -31,8 +30,7 @@ export class WsChatMethodsService {
dmCount = 0;
groupCount = 0;
currentRoom = null
currentRoom: RoomService = null
users: chatUser[] = []
constructor(
@@ -44,31 +42,41 @@ export class WsChatMethodsService {
private sortService: SortService,
private ChatService: ChatService,
private NfService: NfService,
private changeProfileService: ChangeProfileService,
) {
(async()=>{
await this.restoreRooms()
await this.getAllRooms();
this.subscribeToRoom()
this.loadChat()
//
await this.getUser()
this.getUserStatus()
})()
/**
* @description when the phone is in the background for a long time it could disconnects from the socket then the socket reconnects automatically,
* when the connection is lost the subscribe is also lost, so we have to subscribe again when reconnection is establish.
*/
this.WsChatService.registerCallback({
type: 'reConnect',
funx: ()=>{
/**
* @description when the phone is in the background for a long time it could disconnects from the socket then the socket reconnects automatically,
* when the connection is lost the subscribe is also lost, so we have to subscribe again when reconnection is establish.
*/
this.subscribeToRoom()
if(this.currentRoom) {
this.currentRoom.loadHistory({forceUpdate: true})
}
for (const id in this.dm) {
this.dm[id].hasLoadHistory = false
}
for (const id in this.group) {
this.group[id].hasLoadHistory = false
}
}
})
this.changeProfileService.registerCallback(()=>{
this.clearChat()
this.ReLoadChat()
this.storage.remove('Rooms');
})
// this.WsChatService.registerCallback({
// type:'Onmessage',
@@ -104,33 +112,58 @@ export class WsChatMethodsService {
}
private loadChat() {
this.ReLoadChat()
}
async ReLoadChat() {
await this.restoreRooms()
await this.getAllRooms();
this.subscribeToRoom()
//
await this.getUser()
this.getUserStatus()
}
clearChat() {
this.dm = {}
this.group = {}
this._dm = []
this._group = []
this.loadingWholeList = false
this.dmCount = 0;
this.groupCount = 0;
this.currentRoom = null
this.users = []
}
getRoomFromDb() {
this.storage.get('Rooms').then((rooms) => {
rooms.result.update.forEach((roomData: room) => {
this.prepareRoom(roomData);
});
})
};
}
openRoom(roomId) {
if(this.currentRoom) {
if(this.getDmRoom(this.currentRoom)) {
this.getDmRoom(this.currentRoom).roomLeave()
} else if(this.getGroupRoom(this.currentRoom)) {
this.getGroupRoom(this.currentRoom).roomLeave()
}
this.currentRoom.roomLeave()
}
this.currentRoom = roomId
if(this.currentRoom) {
if(this.getDmRoom(this.currentRoom)) {
this.getDmRoom(this.currentRoom).open()
} else if(this.getGroupRoom(this.currentRoom)) {
this.getGroupRoom(this.currentRoom).open()
}
if(this.getDmRoom(roomId)) {
this.currentRoom = this.getDmRoom(roomId)
} else if(this.getGroupRoom(roomId)) {
this.currentRoom = this.getGroupRoom(roomId)
}
this.currentRoom.open()
}
@@ -210,7 +243,7 @@ export class WsChatMethodsService {
this.prepareRoom(roomData);
this.getGroupRoom(id).loadHistory();
this.getGroupRoom(id).loadHistory({});
}
+16 -7
View File
@@ -36,6 +36,7 @@ export class WsChatService {
this.ws.registerCallback({
type:'Onmessage',
key:'ping-pong',
funx:(message: any) => {
if(message.msg == "ping") {
this.ws.send({message:{msg:"pong"}, loginRequired: false})
@@ -79,7 +80,9 @@ export class WsChatService {
this.isLogin = true
this.loginResponse = message
this.ws.wsMsgQueue()
setTimeout(()=>{
this.ws.wsMsgQueue()
}, 10)
resolve(message)
}
@@ -155,9 +158,7 @@ export class WsChatService {
}
// send message to room
send({roomId, msg, attachments = null, file = null}) {
const requestId = uuidv4()
send({roomId, msg, attachments = null, file = null, requestId = uuidv4()}) {
var message = {
msg: "method",
@@ -176,7 +177,7 @@ export class WsChatService {
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId ) { // same request send
resolve(message)
resolve({message, requestId})
return true
}
}})
@@ -273,7 +274,7 @@ export class WsChatService {
return new Promise ((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message) =>{
if(message.id == requestId || deepFind(message, 'result') == requestId){
if(message.id == requestId ){
resolve(message)
return true
}
@@ -629,7 +630,11 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) {
console.log('================== welcome to socket server =====================')
this.ws.wsMsgQueue()
setTimeout(()=>{
this.ws.wsMsgQueue()
}, 10)
if(this.wsReconnect >= 1) {
for (const [key, value] of Object.entries(this.wsCallbacks)) {
if(value.type== 'reConnect') {
@@ -671,6 +676,8 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) {
this.wsMsgQueue[requestId] = {message, requestId, loginRequired}
} else {
let messageStr = JSON.stringify(message)
// console.log('messageStr', messageStr)
this.socket.send(messageStr)
}
return requestId
@@ -679,6 +686,8 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) {
onmessage: async (event: any)=> {
const data = JSON.parse(event.data)
// console.log('onmessage', data)
for (const [key, value] of Object.entries(this.wsCallbacks)) {
if(value.type== 'Onmessage') {
const dontRepeat = await value.funx(data)
@@ -49,12 +49,12 @@
<div class="message-item-options d-flex justify-content-end">
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"></fa-icon>
<mat-menu #beforeMenu="matMenu" xPosition="before">
<button (click)="deleteMessage(msg._id, msg)" class="menuButton">Apagar mensagem</button>
<button (click)="deleteMessage(msg._id)" class="menuButton">Apagar mensagem</button>
</mat-menu>
</div>
<div class="title">
<ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div class="message">
<ion-label>{{msg.msg}}</ion-label>
@@ -68,11 +68,11 @@
<div class="message-item-options d-flex justify-content-end">
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"></fa-icon>
<mat-menu #beforeMenu="matMenu" xPosition="before">
<button (click)="deleteMessage(msg._id, msg)" class="menuButton">Apagar mensagem</button>
<button (click)="deleteMessage(msg._id)" class="menuButton">Apagar mensagem</button>
</mat-menu>
</div>
<div class="title">
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div class="message">
<div *ngIf="msg.attachments" class="message-attachments">
@@ -126,7 +126,7 @@
</div>
<div class="title">
<ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div>
<ion-label>{{msg.msg}}</ion-label>
@@ -234,7 +234,7 @@
<div class="width-100">
<ion-item class="ion-no-padding type-message" lines="none">
<ion-textarea autocomplete="on" autocorrect="on" spellcheck="true" (keyup.enter)="sendMessage()" clearOnEdit="true" placeholder="Escrever uma mensagem" class="message-input" rows="1" [(ngModel)]="wsChatMethodsService.getGroupRoom(roomId).message" (ionChange)="changeInput()"></ion-textarea>
<ion-textarea autocomplete="on" autocorrect="on" spellcheck="true" (keyup.enter)="sendMessage()" clearOnEdit="true" placeholder="Escrever uma mensagem" class="message-input" rows="1" [(ngModel)]="wsChatMethodsService.getGroupRoom(roomId).message" (ionChange)="wsChatMethodsService.getGroupRoom(roomId).sendTyping()"></ion-textarea>
<button hidden class="btn-no-color">
<ion-icon slot="end" src="assets/icon/icons-chat-mic.svg"></ion-icon>
</button>
@@ -121,7 +121,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
this.getRoomInfo();
//this.scrollToBottom();
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory();
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory({});
// console.log('MESSAGES'+ this.wsChatMethodsService.getGroupRoom(this.roomId).messages);
this.wsChatMethodsService.openRoom(this.roomId)
this.wsChatMethodsService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked
@@ -230,9 +230,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
}
changeInput() {
this.wsChatMethodsService.getDmRoom(this.roomId).typing()
}
async getChatMembers() {
//return await this.chatService.getMembers(roomId).toPromise();
@@ -272,7 +269,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
}
async getRoomInfo() {
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory();
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory({});
let room = await this.chatService.getRoomInfo(this.roomId).toPromise();
this.room = room['room'];
if (this.room.name) {
@@ -310,7 +307,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
this.wsChatMethodsService.getGroupRoom(this.roomId).send({})
}
deleteMessage(msgId: string, room:any) {
deleteMessage(msgId: string) {
const room = this.wsChatMethodsService.getGroupRoom(this.roomId)
this.alertService.confirmDeleteMessage(msgId, room);
}
@@ -632,7 +630,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
const data = res.data;
if(data.selected) {
const loader = this.toastService.loading();
this.wsChatMethodsService.getGroupRoom(roomId).send({
file:{
@@ -657,7 +654,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
temporaryData: res
})
loader.remove();
}
});
@@ -34,8 +34,7 @@ export class ContactsPage implements OnInit {
private authService: AuthService,
public ThemeService: ThemeService,
public WsChatMethodsService: WsChatMethodsService
)
{
) {
this.loggedUser = authService.ValidatedUserChat['data'];
this.textSearch="";
this.dm=null;
@@ -44,12 +44,12 @@
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer">
</fa-icon>
<mat-menu #beforeMenu="matMenu" xPosition="before">
<button (click)="deleteMessage(msg._id, msg)" class="menuButton">Apagar mensagem</button>
<button (click)="deleteMessage(msg._id)" class="menuButton">Apagar mensagem</button>
</mat-menu>
</div>
<div class="title">
<ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div>
<ion-label>{{msg.msg}}</ion-label>
@@ -63,12 +63,12 @@
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer">
</fa-icon>
<mat-menu #beforeMenu="matMenu" xPosition="before">
<button (click)="deleteMessage(msg._id, msg)" class="menuButton">Apagar mensagem</button>
<button (click)="deleteMessage(msg._id)" class="menuButton">Apagar mensagem</button>
</mat-menu>
</div>
<div class="title">
<ion-label>{{msg.u.name}} </ion-label>
<span class="time">{{showDateDuration(msg.duration)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div>
<div *ngIf="msg.attachments" class="message-attachments">
@@ -134,7 +134,7 @@
</div>
<div class="title">
<ion-label>{{msg.u.name}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span>
<span class="time">{{msg.duration}}</span>
</div>
<div>
<ion-label>{{msg.msg}}</ion-label>
@@ -215,7 +215,7 @@
<div class="width-100">
<ion-item class="ion-no-padding type-message" lines="none">
<ion-textarea (keyup.enter)="sendMessage()" clearOnEdit="true" placeholder="Escrever uma mensagem"
class="message-input" rows="1" [(ngModel)]="wsChatMethodsService.getDmRoom(roomId).message" (ionChange)="changeInput()"></ion-textarea>
class="message-input" rows="1" [(ngModel)]="wsChatMethodsService.getDmRoom(roomId).message" (ionChange)="wsChatMethodsService.getDmRoom(roomId).sendTyping()"></ion-textarea>
<button hidden class="btn-no-color" (click)="notImplemented()">
<ion-icon slot="end" src="assets/icon/icons-chat-mic.svg"></ion-icon>
</button>
@@ -111,7 +111,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}
ngOnChanges(changes: SimpleChanges): void {
this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory()
this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory({})
this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked
@@ -125,7 +125,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
this.scrollToBottomClicked()
}, 150)
}
ngOnInit() {
@@ -251,7 +250,8 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
this.wsChatMethodsService.getDmRoom(this.roomId).send({})
}
deleteMessage(msgId: string, room:any) {
deleteMessage(msgId: string) {
const room = this.wsChatMethodsService.getDmRoom(this.roomId)
this.alertService.confirmDeleteMessage(msgId, room);
}
@@ -278,9 +278,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}
}
changeInput() {
this.wsChatMethodsService.getDmRoom(this.roomId).typing()
}
async openViewDocumentModal(file: any) {
let task = {
@@ -533,7 +530,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
const roomId = this.roomId
if(data.selected) {
const loader = this.toastService.loading();
this.wsChatMethodsService.getDmRoom(roomId).send({
file:{
@@ -553,7 +549,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}],
})
loader.remove();
}
});
@@ -29,7 +29,7 @@ export class EditActionPage implements OnInit {
public stepSecond = 5;
public dateControlStart = new FormControl(moment("DD MM YYYY hh"));
public dateControlEnd = new FormControl(moment("DD MM YYYY hh"));
folder: PublicationFolder;
@Input() folderId: string;
@Output() closeDesktopComponent= new EventEmitter<any>();
@@ -39,7 +39,7 @@ export class EditActionPage implements OnInit {
constructor(
private publicationsService: PublicationsService,
private toastService: ToastService,
) {
) {
this.folder = new PublicationFolder();
}
@@ -54,7 +54,7 @@ export class EditActionPage implements OnInit {
getPublicationDetail() {
this.publicationsService.GetPresidentialAction(this.folderId).subscribe( res => {
this.folder = res;
this.dateControlStart = new FormControl(moment(new Date(this.folder.DateBegin)));
this.dateControlEnd = new FormControl(moment(new Date(this.folder.DateEnd)));
@@ -62,7 +62,7 @@ export class EditActionPage implements OnInit {
}
get dateValid() {
if (window.innerWidth <= 800) {
if (window.innerWidth < 701) {
return this.folder.DateBegin < this.folder.DateEnd? ['ok']: []
} else {
return ['ok']
@@ -96,7 +96,7 @@ export class EditActionPage implements OnInit {
ActionType: this.folder.ActionType,
}
console.log(body);
const loader = this.toastService.loading()
try {
@@ -111,6 +111,6 @@ export class EditActionPage implements OnInit {
} finally {
loader.remove()
}
}
}
@@ -70,7 +70,7 @@ export class NewActionPage implements OnInit {
}
get dateValid() {
if (window.innerWidth >= 800) {
if (window.innerWidth > 700) {
return new Date(this.folder.DateBegin).toLocaleString('pt') < new Date(this.folder.DateEnd).toLocaleString("pt")? ['ok'] : []
} else {
return ['ok']
@@ -108,7 +108,7 @@ export class PublicationDetailPage implements OnInit {
async editPost(publicationType:any) {
console.log(this.publication);
if(window.innerWidth <= 1024){
if(window.innerWidth < 701){
const modal = await this.modalController.create({
component: NewPublicationPage,
componentProps:{
@@ -180,7 +180,7 @@ export class ViewPublicationsPage implements OnInit {
async AddPublication(publicationType:any, folderId:any) {
if( window.innerWidth <= 1024) {
if( window.innerWidth < 701) {
const modal = await this.modalController.create({
component: NewPublicationPage,
componentProps:{
+1 -1
View File
@@ -13,7 +13,7 @@ export const environment = {
domain: 'gabinetedigital.local', //gabinetedigital.local
defaultuser: 'paulo.pinto@gabinetedigital.local',//paulo.pinto paulo.pinto@gabinetedigital.local
defaultuserpwd: 'tabteste@006', //tabteste@006,
chatOffline: true
chatOffline: false
};
/*