Files
doneit-web/src/app/services/chat/room.service.ts
T
tiago.kayaya 4c43a81a1d save
2022-01-28 19:09:37 +01:00

457 lines
12 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 { ChatUserService } from 'src/app/services/chat/chat-user.service';
import { showDateDuration } from 'src/plugin/showDateDuration';
import { ToastsService } from '../toast.service';
import { chatHistory, ChatMessage } 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';
@Injectable({
providedIn: 'root'
})
export class RoomService {
messages: MessageService[] = []
storageMessage: any[] = [];
lastMessage: MessageService;
chatUser: ChatUserService[] = []
customFields: any;
id = ''
t = ''
name = ''
_updatedAt = {}
private hasLoadHistory = false
duration = ''
isTyping = false
otherUserType = false
lastTimeType = null
message = ''
lastMessageTxt = ''
userThatIsTyping = ''
private ToastService = ToastsService
mgsArray = [];
scrollDown = () => { }
constructor(
public WsChatService: WsChatService,
private MessageService: MessageService,
private storage: Storage,
private platform: Platform,
private sqlservice: SqliteService,
private NativeNotificationService: NativeNotificationService,
private sortService: SortService,
) {
this.NativeNotificationService.askForPermission()
}
setData({ customFields, id, name, t, lastMessage = new MessageService(this.storage), _updatedAt }) {
this.customFields = customFields
this.id = id
this.name = name
this.t = t
this.lastMessage = lastMessage
this._updatedAt = _updatedAt
this.calDateDuration()
}
receiveMessage() {
this.WsChatService.updateRoomEventss(
this.id,
"stream-room-messages",
(ChatMessage) => {
ChatMessage = ChatMessage.fields.args[0]
ChatMessage = this.fix_updatedAt(ChatMessage)
console.log('recivemessage', ChatMessage)
/* this.ToastService._chatMessage({message:'Nova mensagem', sender:'Gilson'}) */
const message = new MessageService(this.storage)
message.setData(ChatMessage)
this.lastMessage = message
if (message.t == 'r') { this.name = message.msg }
this.calDateDuration(ChatMessage._updatedAt)
this.messages.push(message)
setTimeout(() => {
this.scrollDown()
}, 100)
//this.sortService.sortDate(this.messages, '')
if(SessionStore.user.RochetChatUser != ChatMessage.u.username) {
this.NativeNotificationService.sendNotificationChat({
message: message.msg,
title: this.name
});
}
// save to ionic storage
this.storage.get('chatmsg' + this.id).then((messages: any) => {
const newListMessages = messages.push(ChatMessage)
this.storage.set('chatmsg' + this.id, newListMessages).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
});
})
}
)
this.WsChatService.receiveStreamNotifyRoom((message) => {
if(message.fields.eventName == this.id+'/'+'typing') {
this.userThatIsTyping = this.usernameToDisplayName(message.fields.args[0])
this.isTyping = message.fields.args[1]
this.otherUserType = message.fields.args[1]
} else if (message.fields.eventName == this.id+'/'+'deleteMessage') {}
})
this.WsChatService.registerCallback
}
async receiveMessageDelete() {
this.WsChatService.updateRoomEventss(
this.id,
"stream-notify-room",
async (ChatMessage) => {
console.log(ChatMessage.fields.args[0]._id);
const messageId = ChatMessage.fields.args[0]._id;
this.messages.forEach((message, index)=>{
if(message._id == messageId){
this.messages.splice(index, 1)
this.storage.set('chatmsg' + this.id, this.messages).then((value) => {
//console.log('MSG DELETE ON STORAGE', value)
});
//Get previous last message from room
const previousLastMessage = this.messages.slice(-1)[0];
this.lastMessage = previousLastMessage;
this.calDateDuration(previousLastMessage._updatedAt)
}
})
}
)
this.WsChatService.registerCallback
}
send() {
this.WsChatService.send(this.id, this.message)
this.message= ''
}
typing(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.RochetChatUser, 'typing', this.isTyping)
}
this.lastMessageTxt = this.message
this.typingWatch()
}
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.RochetChatUser, 'typing', this.isTyping)
}
} else {
//console.log(now - this.lastTimeType)
}
}, 3000)
}
leave(rid?) {
this.WsChatService.leaveRoom(this.id)
}
getMsgFromDBMobile() {
console.log('ALL MSG DBBB', this.id)
this.sqlservice.getAllChatMSG(this.id).then((msg: any = []) => {
let ad = [];
ad = msg
console.log('ALL MSG DBBB', ad.length)
msg.map(element => {
console.log('CHANNEL ELEMENT', element)
let msgChat = {
_id: element.Id,
attachments: this.isJson(element.Attachments),
channels: this.isJson(element.Channels),
file: {
guid: this.isJson(element.File).guid,
image_url: this.isJson(element.image_url),
type: this.isJson(element.File).type
},
mentions: this.isJson(element.Mentions),
msg: element.Msg,
rid: element.Rid,
ts: element.Ts,
u: this.isJson(element.U),
_updatedAt: this.isJson(element.UpdatedAt),
}
let mmessage = this.fix_updatedAt(msgChat)
console.log('FROM DB WEB', mmessage)
const wewMessage = new MessageService(this.storage)
wewMessage.setData(mmessage)
this.messages.push(wewMessage)
console.log('loadHistory 222', this.messages)
});
});
}
isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return "";
}
return JSON.parse(str);
}
getMsgFromDB() {
/* this.storage.get('chatmsg' + this.id).then((message) => {
console.log('ALL MESSAGE WEB', message)
message.forEach(message => {
if (message.file) {
if (message.file.guid) {
this.storage.get(message.file.guid).then((image) => {
//console.log('IMAGE FROM STORAGE', image)
message.file.image_url = image
});
}
}
let mmessage = this.fix_updatedAt(message)
console.log('FROM DB WEB', mmessage)
const wewMessage = new MessageService(this.storage)
wewMessage.setData(mmessage)
this.messages.push(wewMessage)
console.log('loadHistory 222', this.messages)
});
}) */
}
// runs onces only
loadHistory(limit = 100) {
if (this.hasLoadHistory) { return false }
this.storage.get('chatmsg' + this.id).then((messages = [])=>{
let localMessages = []
messages.forEach(message => {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage)
wewMessage.setData(message)
localMessages.push(wewMessage)
});
this.messages = localMessages
})
this.WsChatService.loadHistory(this.id, limit).then((chatHistory:chatHistory) => {
console.log('loadHistory', chatHistory)
let localMessages = []
//const sortedRoomList = this.sortService.sortDate(chatHistory.result.messages, "_updatedAt.$date")
chatHistory.result.messages.reverse().forEach(message => {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage)
wewMessage.setData(message)
localMessages.push(wewMessage)
});
this.messages = localMessages
console.log(chatHistory.result.messages);
this.storage.set('chatmsg' + this.id, chatHistory.result.messages.reverse())
})
/* this.WsChatService.loadHistory(this.id, limit).then(async (chatHistory: chatHistory) => {
const mgsArray = chatHistory.result.messages.reverse();
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
await this.storage.remove('chatmsg' + this.id).then(() => {
console.log('MSG REMOVE ON STORAGE')
})
await this.storage.set('chatmsg' + this.id, mgsArray).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
this.getMsgFromDB()
});
} else {
mgsArray.forEach((element) => {
console.log('SQLITE WEBSOCKET', element)
this.sqlservice.addChatMSG(element)
})
this.getMsgFromDBMobile()
}
}) */
setTimeout(() => {
this.scrollDown()
}, 50)
this.hasLoadHistory = true
}
updateMeessage(messageID, imgbase64) {
}
async returnData(res) {
return res;
}
async transformData(res) {
this.mgsArray = [];
res.forEach(async element => {
if (element.file) {
if (element.file.guid) {
await this.storage.get(element.file.guid).then((image) => {
let chatmsg = {
_id: element._id,
attachments: element.attachments,
channels: element.channels,
file: {
guid: element.file.guid,
image_url: image,
type: element.file.type
},
mentions: element.mentions,
msg: element.msg,
rid: element.rid,
ts: element.ts,
u: element.u,
_updatedAt: element._updatedAt,
}
this.mgsArray.push(chatmsg);
})
} else {
let chatmsg = {
_id: element._id,
attachments: element.attachments,
channels: element.channels,
file: element.file,
mentions: element.mentions,
msg: element.msg,
rid: element.rid,
ts: element.ts,
u: element.u,
_updatedAt: element._updatedAt,
}
this.mgsArray.push(chatmsg)
}
} else {
let chatmsg = {
_id: element._id,
attachments: element.attachments,
channels: element.channels,
mentions: element.mentions,
msg: element.msg,
rid: element.rid,
ts: element.ts,
u: element.u,
_updatedAt: element._updatedAt,
}
this.mgsArray.push(chatmsg)
}
});
await this.storage.remove('chatmsg').then(() => {
console.log('MSG REMOVE FROM STORAGE')
});
await this.storage.set('chatmsg', this.mgsArray).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
});
}
ReactToMessage() { }
private calDateDuration(date = null) {
this.duration = showDateDuration(date || this._updatedAt);
this._updatedAt = date || this._updatedAt
}
private fix_updatedAt(message) {
if (message.result) {
console.log('FIX UPDATE ', message.result)
message.result._updatedAt = message.result._updatedAt['$date']
} else {
console.log('FIX UPDATE 11', message)
message._updatedAt = message._updatedAt['$date']
}
return message
}
usernameToDisplayName(username) {
const firstName = capitalizeTxt(username.split('.')[0])
const lastName = capitalizeTxt(username.split('.')[1])
return firstName + ' ' + lastName
}
}