Files
doneit-web/src/app/services/chat/room.service.ts
T
2022-04-28 09:32:27 +01:00

820 lines
20 KiB
TypeScript

import { Injectable } from '@angular/core';
import { WsChatService } from 'src/app/services/chat/ws-chat.service';
import { MessageService } from 'src/app/services/chat/message.service';
import { showDateDuration } from 'src/plugin/showDateDuration';
import { ToastsService } from '../toast.service';
import { chatHistory } from 'src/app/models/chatMethod';
import { Storage } from '@ionic/storage';
import { Platform } from '@ionic/angular';
import { SqliteService } from 'src/app/services/sqlite.service';
import { NativeNotificationService } from 'src/app/services/native-notification.service';
import { SessionStore } from 'src/app/store/session.service';
import { capitalizeTxt } from 'src/plugin/text'
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 { v4 as uuidv4 } from 'uuid'
import { ChatStorageService } from './chat-storage.service'
import { ChatMethodsService } from './chat-methods.service'
import { DeleteMessageModel, MessageModel } from '../../models/beast-orm'
import { AESEncrypt } from '../aesencrypt.service'
import { IncomingChatMessage, ChatMessageInterface, falseTypingMethod } from 'src/app/models/message.model';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { ConnectionStatus, NetworkServiceService} from 'src/app/services/network-service.service';
@Injectable({
providedIn: 'root'
})
export class RoomService {
messages: MessageService[] = []
storageMessage: any[] = [];
lastMessage: MessageService;
customFields: any;
id = ''
t = ''
name = ''
_updatedAt = {}
hasLoadHistory = false
restoreFromOffline = false
duration = ''
isTyping = false
otherUserType = false
lastTimeType = null
message = ''
lastMessageTxt = ''
userThatIsTyping = ''
mgsArray = [];
messagesLocalReference = []
members = []
u
sessionStore = SessionStore
scrollDown = () => { }
/**
* @description get user list from ws-chat-methods.service
* @returns chatUser[]
*/
getAllUsers = (): chatUser[] => {
return []
}
sortRoomList = () => {}
uploadAttachment = (formData) => {}
constructor(
public WsChatService: WsChatService,
private MessageService: MessageService,
private storage: Storage,
private platform: Platform,
private sqlservice: SqliteService,
private NativeNotificationService: NativeNotificationService,
private sortService: SortService,
private chatService: ChatService,
private NfService: NfService,
private ChatStorageService: ChatStorageService,
private ChatMethodsService: ChatMethodsService,
private AESEncrypt: AESEncrypt,
private AttachmentsService: AttachmentsService,
private NetworkServiceService: NetworkServiceService
) {
this.NativeNotificationService.askForPermission()
this.WsChatService.getUserStatus((d) => {
const userId = d.fields.args[0][0]
const statusNum = d.fields.args[0][2]
const statusText = this.statusNumberToText(statusNum)
if(this.members?.map) {
const membersIds = this.members.map((user)=> user._id)
if(membersIds.includes(userId)) {
if(statusText != 'offline') {
this.deleteMessageToReceive(userId)
}
this.messages.forEach((message, index) => {
if(!message.messageOwnerById(userId)) {
if(!this.messages[index]?.received?.includes(userId)) {
if(this.messages[index]._id) {
try {
if(!this.messages[index].received.includes(userId)) {
this.messages[index].received.push(userId)
}
} catch(e) {
this.messages[index].received = [userId]
}
this.messages[index].save()
}
}
}
})
}
}
})
}
/**
* @description convert rocketchat statues num to readable string
* @param text
* @returns
*/
statusNumberToText(text) {
if(text == '0') {
return "offline"
}
else if(text == '1') {
return "online"
}
else if(text == '2') {
return "away"
}
else if(text == '3') {
return "busy"
}
}
setData({members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService), _updatedAt }) {
this.customFields = customFields
this.id = id
this.name = name
this.t = t
this.lastMessage = lastMessage
this._updatedAt = _updatedAt
this.u = u
this.members = members
this.calDateDuration()
this.restoreMessageFromDB()
}
isSenderIsNotMe(ChatMessage) {
return SessionStore.user.UserName != ChatMessage.u.username
}
senderId(ChatMessage) {
return ChatMessage.u._id
}
receiveMessage() {
this.WsChatService.updateRoomEventss(
this.id,
"stream-room-messages",
async (IncomingChatMessage:IncomingChatMessage) => {
let IncomingChatMessageArgs = IncomingChatMessage.fields.args[0]
let ChatMessage : ChatMessageInterface = this.fix_updatedAt(IncomingChatMessageArgs)
if(!this.messagesLocalReference.includes(ChatMessage.localReference)) {
const message = await this.prepareCreate({message: ChatMessage, save: true})
message.messageSend = true
this.lastMessage = message
this.calDateDuration(ChatMessage._updatedAt)
if (message.t == 'r') {
this.name = message.msg
}
if(this.isSenderIsNotMe(ChatMessage)) {
this.NativeNotificationService.sendNotificationChat({
message: message.msg,
title: this.name
});
}
message.addMessageDB()
setTimeout(()=>{
this.scrollDown()
}, 50)
} else {
this.messages.forEach((message, index)=> {
if(message.localReference == ChatMessage.localReference) {
const membersIds = this.members.map((user)=> user._id)
this.getAllUsers().forEach( async (users) => {
if(membersIds.includes(users._id)) {
if(users.status != 'offline') {
this.messages[index].received.push(users._id)
setTimeout(() => {
message.save()
}, 150)
}
}
});
}
})
}
}
)
this.WsChatService.receiveStreamNotifyRoom((message) => {
if(message.fields.eventName == this.id+'/'+'typing') {
const args = message.fields.args
if (typeof args[1] != 'object') {
this.userThatIsTyping = this.usernameToDisplayName(args[0])
this.isTyping = args[1]
this.otherUserType = args[1]
this.readAllMessage()
//
// alert(JSON.stringify(args))
} else if(args[0]?.method == 'viewMessage' || args[1]?.method == 'viewMessage') {
this.readAllMessage()
} else if(args[0]?.method == 'deleteMessage' || args[1]?.method == 'deleteMessage') {
// alert('delete')
//
this.deleteMessage(args[1]?.method?._id)
} else {
// alert('miss')
}
} else if (message.fields.eventName == this.id+'/'+'deleteMessage') {}
})
}
getRoomMembersIds(): string[] {
try {
return this.members.map((user)=> user._id)
} catch(error) {
return []
}
}
getAllMemberThatIsNotOffline(): string[] {
const membersIds = this.getRoomMembersIds()
const allChatUsers = this.getAllUsers()
const AllMemberThatIsNotOffline = []
for(let user of allChatUsers) {
if(membersIds.includes(user._id)) {
if(user.status != 'offline') {
AllMemberThatIsNotOffline.push(user._id)
}
}
}
return AllMemberThatIsNotOffline
}
getAllMemberThatIsOffline(): string[] {
const membersIds = this.getRoomMembersIds()
const allChatUsers = this.getAllUsers()
const AllMemberThatIsNotOffline = []
for(let user of allChatUsers) {
if(membersIds.includes(user._id)) {
if(user.status == 'offline') {
AllMemberThatIsNotOffline.push(user._id)
}
}
}
return AllMemberThatIsNotOffline
}
async deleteMessageToReceive(userId) {
const allDeleteMessages = await DeleteMessageModel.filter({rid: this.id}).execute()
for(let message_ of allDeleteMessages) {
if(message_.needToReceiveBy.includes(userId)) {
message_.needToReceiveBy = message_.needToReceiveBy.filter((e)=> e != userId)
this.sendFalseTypingReadMessage('deleteMessage',{_id:message_.messageId})
if(message_.needToReceiveBy.length == 0) {
const deleteMessage = await DeleteMessageModel.get({messageId: message_.messageId})
await deleteMessage.delete()
} else {
await DeleteMessageModel.update(message_)
}
}
}
}
async receiveMessageDelete() {
this.WsChatService.updateRoomEventss(
this.id,
"stream-notify-room",
async (ChatMessage) => {
const DeletedMessageId = ChatMessage.fields.args[0]._id;
this.deleteMessage(DeletedMessageId)
}
)
}
/**
* @description delete message in the view
* @param id message ID
*/
async deleteMessage(_id) {
const id = _id
for (let i =0; i <= this.messages.length; i++) {
if(this.messages[i]?._id == id ) {
if (SessionStore.user.UserName == this.messages[i]?.u?.username) {
const allMemberThatIsOffline = this.getAllMemberThatIsOffline()
DeleteMessageModel.create({
messageId: this.messages[i]._id,
rid: this.messages[i].rid,
ts: this.messages[i].ts,
u: this.messages[i].u,
needToReceiveBy: allMemberThatIsOffline
})
}
this.messages[i]?.delateDB()
this.messages.splice(i, 1)
//Get previous last message from room
const previousLastMessage = this.messages.slice(-1)[0];
this.lastMessage = previousLastMessage;
this.calDateDuration(previousLastMessage._updatedAt)
this.sortRoomList()
return true
} else {
//
}
}
}
deleteAll() {
this.messages.forEach((message)=>{
if(message?._id) {
this.sendDeleteRequest(message._id)
}
})
}
async delateMessageToSendToOthers(userId) {
const deleteMessage = await DeleteMessageModel.all()
const toSend = deleteMessage.filter((DeleteMessage:string[])=> ! DeleteMessage.includes(userId))
}
async sendDeleteRequest(msgId) {
const message = this.messages.find((e)=>e._id == msgId)
await message.delateStatusFalse()
if(this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) {
this.WsChatService.deleteMessage(msgId).then(async() => {
message.delateRequest = true
await message.save()
this.deleteMessage(msgId)
})
} else {
this.WsChatService.registerCallback({
type: 'reConnect',
funx: async ()=> {
this.sendDeleteRequest(msgId)
return true
}
})
}
}
/**
* @description sen text message
*/
async send({file = null, attachments = null, temporaryData = {}}) {
const localReference = uuidv4()
let offlineChatMessage = {
rid: this.id,
msg: this.message,
attachments,
file,
temporaryData,
localReference
}
this.message= ''
const message: MessageService = await this.prepareCreate({message:offlineChatMessage, save: environment.chatOffline})
this.messagesLocalReference.push(localReference)
await message.addMessageDB()
message.send()
if (environment.chatOffline) {
setTimeout(() => {
this.scrollDown()
}, 150)
this.lastMessage = message
this.calDateDuration(message._updatedAt)
this.sortRoomList()
}
}
sendTyping(text:string = this.message) {
if(this.lastMessageTxt == text) { return false }
this.lastTimeType = new Date().getTime()
const lastIsTyping = this.isTyping
if(text.length >= 1) {
this.isTyping = true
} else {
this.isTyping = false
}
if(lastIsTyping != this.isTyping) {
this.WsChatService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', this.isTyping)
}
this.lastMessageTxt = this.message
this.typingWatch()
}
sendFalseTypingReadMessage(method,param: object) {
this.WsChatService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', {method:method, params: param} as falseTypingMethod)
this.setTypingOff()
}
private typingWatch() {
setTimeout(()=>{
const now = new Date().getTime()
if((now - this.lastTimeType) >= 2888) {
if(this.isTyping == true) {
this.isTyping = false
this.WsChatService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', this.isTyping)
}
} else {
}
}, 3000)
}
private setTypingOff() {
this.sendTyping('')
}
roomLeave() {
this.setTypingOff()
}
open() {
// this.typing(this.message)
}
leave(rid?) {
this.WsChatService.leaveRoom(this.id)
}
isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return "";
}
return JSON.parse(str);
}
async restoreMessageFromDB() {
if(environment.chatOffline) {
const messages = await MessageModel.filter({rid:this.id}).execute()
await messages.forEach( async (ChatMessage, index) => {
const wewMessage = await this.simplePrepareMessage(ChatMessage)
if(wewMessage.offline == false) {
const message = await this.prepareMessageCreateIfNotExist_iD({message:ChatMessage})
message?.decryptMessage()
} else {
const offlineMessage = await this.prepareMessageCreateIfNotExist({message:ChatMessage})
if(offlineMessage) {
this.messagesLocalReference.push(offlineMessage.localReference)
offlineMessage?.decryptMessage()
offlineMessage.send()
}
}
if(wewMessage.delate && !wewMessage.offline && !wewMessage.delateRequest) {
this.sendDeleteRequest(wewMessage._id)
}
});
setTimeout(()=> {
this.scrollDown()
}, 50)
}
}
// runs onces only
async loadHistory({limit = 1000, forceUpdate = false }) {
if(forceUpdate == false) {
if (this.hasLoadHistory) {
return false
}
}
if(this.restoreFromOffline == false) {
this.restoreFromOffline = true
await this.restoreMessageFromDB()
}
await this.WsChatService.loadHistory(this.id, limit).then( async (chatHistory:chatHistory) => {
//
const messagesId = this.messages.map((message)=> message._id)
chatHistory.result.messages.reverse().forEach(async(message: any) => {
if (!messagesId.includes(message._id)) {
const messagesToSave = await this.prepareMessageCreateIfNotExist_iD({message: message});
if(messagesToSave) {
await messagesToSave.addMessageDB()
}
}
})
})
setTimeout(() => {
this.scrollDown()
}, 50)
this.hasLoadHistory = true
}
async readAllMessage() {
const membersIds = this.members.map((user)=> user._id)
await this.messages.forEach( async (message, index) => {
if(message._id) {
if(message.viewed.length == 0) {
this.messages[index].viewed = membersIds
this.messages[index].received = membersIds
await this.messages[index].save()
}
}
})
}
/**
* @description find or create message
* @param message
* @param save
* @returns
*/
async prepareMessage({message, save = true, redefined = false}): Promise<MessageService> {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService)
wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory
let foundIndex;
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == message._id) {
foundIndex = index
return true
} else {
return false
}
})
if(save) {
if (!found) {
this.messages.push(wewMessage)
return wewMessage
}
} else if(foundIndex) {
return this.messages[foundIndex]
} else {
return wewMessage
}
}
async ChatMessageIsPresentInTheView(ChatMessage:ChatMessageInterface) {
let foundIndex;
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == ChatMessage._id) {
foundIndex = index
return true
} else {
return false
}
})
if (foundIndex) {
return { found, foundIndex}
} else {
return false
}
}
/**
* @description find or create message
* @param message
* @param save
* @returns
*/
async prepareCreate({message, save = true}): Promise<MessageService> {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService)
wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory
this.messages.push(wewMessage)
return wewMessage
}
simplePrepareMessage(message) {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService, this.ChatStorageService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService)
wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory
return wewMessage
}
async prepareMessageCreateIfNotExist({message}) {
message = this.fix_updatedAt(message)
let foundIndex;
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == message._id ||
MessageService.localReference == message.localReference ) {
foundIndex = index
return true
} else {
return false
}
})
if (!found) {
const wewMessage = this.simplePrepareMessage(message)
this.messages.push(wewMessage)
return wewMessage
} else {
return null
}
}
async prepareMessageCreateIfNotExist_iD({message}) {
message = this.fix_updatedAt(message)
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == message._id ) {
return true
} else {
return false
}
})
if (!found) {
const wewMessage = this.simplePrepareMessage(message)
this.messages.push(wewMessage)
return wewMessage
} else {
return null
}
}
private calDateDuration(date = null) {
this.duration = showDateDuration(date || this._updatedAt);
this._updatedAt = date || this._updatedAt
}
private fix_updatedAt(message): ChatMessageInterface {
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
}
usernameToDisplayName(username) {
const firstName = capitalizeTxt(username.split('.')[0])
const lastName = capitalizeTxt(username.split('.')[1])
return firstName + ' ' + lastName
}
sendReadMessage() {
this.WsChatService.readMessage(this.id)
this.sendFalseTypingReadMessage('viewMessage', {})
}
}