Merge with websocket branch

This commit is contained in:
Eudes Inácio
2022-01-19 09:12:30 +01:00
46 changed files with 1631 additions and 729 deletions
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ChatUserService } from './chat-user.service';
describe('ChatUserService', () => {
let service: ChatUserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ChatUserService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,9 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ChatUserService {
constructor() { }
}
@@ -1,13 +1,13 @@
import { TestBed } from '@angular/core/testing';
import { MethodsService } from './methods.service';
import { MessageService } from './message.service';
describe('MethodsService', () => {
let service: MethodsService;
describe('MessageService', () => {
let service: MessageService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MethodsService);
service = TestBed.inject(MessageService);
});
it('should be created', () => {
+44
View File
@@ -0,0 +1,44 @@
import { Injectable } from '@angular/core';
import { Message } from 'src/app/models/chatMethod';
import { chatHistory, ChatMessage, File } from 'src/app/models/chatMethod'
@Injectable({
providedIn: 'root'
})
export class MessageService {
customFields
channels = []
mentions = []
msg = ''
rid = ''
ts = {}
u = {}
t = ''
_id =''
_updatedAt = {}
file
attachments
constructor() { }
setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments}:Message) {
this.customFields = customFields
this.channels = channels
this.mentions = mentions
this.msg = msg
this.rid = rid
this.ts = ts
this.u = u
this.t = t
this._id = _id
this._updatedAt = _updatedAt
this.file = file
this.attachments = attachments
}
delete() {}
showDateDuration() {}
}
-11
View File
@@ -1,11 +0,0 @@
import { Injectable } from '@angular/core';
import { ChatService } from '../chat.service';
@Injectable({
providedIn: 'root'
})
export class MethodsService {
constructor(private chatService: ChatService) {
}
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { RoomService } from './room.service';
describe('RoomService', () => {
let service: RoomService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(RoomService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
+197
View File
@@ -0,0 +1,197 @@
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';
@Injectable({
providedIn: 'root'
})
export class RoomService {
massages: MessageService[] = []
lastMessage: MessageService;
chatUser: ChatUserService[] = []
customFields:any;
id = ''
t = ''
name = ''
_updatedAt = {}
private hasLoadHistory = false
duration = ''
private ToastService = ToastsService
scrollDown = () => {}
constructor(
public WsChatService: WsChatService,
private MessageService: MessageService,
private storage: Storage,
) {}
setData({customFields, id, name, t, lastMessage, _updatedAt}) {
this.customFields = customFields
this.id = id
this.name = name
this.t = t
this.lastMessage = lastMessage
this._updatedAt = _updatedAt
this.calDateDuration()
}
receiveMessage() {
this.WsChatService.receiveLiveMessageFromRoom(
this.id,
(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()
message.setData(ChatMessage)
this.lastMessage.msg = message.msg
if(message.t == 'r'){this.name = message.msg}
this.calDateDuration(ChatMessage._updatedAt)
this.massages.push(message)
setTimeout(()=>{
this.scrollDown()
}, 100)
}
)
}
send(msg) {
this.WsChatService.send(this.id, msg)
}
// runs onces only
loadHistory(limit= 100) {
if(this.hasLoadHistory){ return false}
this.WsChatService.loadHistory(this.id, limit).then(async (chatHistory:chatHistory) => {
await this.transformData(chatHistory.result.messages.reverse());
chatHistory.result.messages.reverse().forEach(message => {
message = this.fix_updatedAt(message)
console.log('loadHistory', message)
const wewMessage = new MessageService()
wewMessage.setData(message)
this.massages.push(wewMessage)
});
})
setTimeout(()=>{
this.scrollDown()
}, 50)
this.hasLoadHistory = true
}
async transformData(res) {
let mgsArray = [];
res.forEach(async element => {
console.log('TRANSFORM DATA ELEMENT' ,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,
}
mgsArray.push(this.fix_updatedAt(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,
}
mgsArray.push(this.fix_updatedAt(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,
}
mgsArray.push(this.fix_updatedAt(chatmsg))
}
});
await this.storage.remove('chatmsg').then(() => {
console.log('MSG REMOVE FROM STORAGE')
});
await this.storage.set('chatmsg', mgsArray).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
});
}
ReactToMessage() {}
private calDateDuration(date = null) {
this.duration = showDateDuration(date || this._updatedAt);
}
private fix_updatedAt(message) {
if(message.result) {
message.result._updatedAt = message.result._updatedAt['$date']
} else{
message._updatedAt = message._updatedAt['$date']
}
return message
}
// to add
countDownDate(){}
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { WebsocketService } from './websocket.service';
describe('WebsocketService', () => {
let service: WebsocketService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(WebsocketService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,43 @@
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';
@Injectable({
providedIn: 'root'
})
export class WebsocketService {
constructor() { }
private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if(!this.subject){
this.subject = this.create(url);
console.log("Sucessful connect :"+url);
}
return this.subject;
}
private create(url): Rx.Subject<MessageEvent>{
let ws = new WebSocket(url);
let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws)
})
let observer = {
next: (data: Object) => {
if(ws.readyState === WebSocket.OPEN){
ws.send(JSON.stringify(data));
}
}
}
return Rx.Subject.create(observer, observable);
}
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { WsChatMethodsService } from './ws-chat-methods.service';
describe('WsChatMethodsService', () => {
let service: WsChatMethodsService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(WsChatMethodsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,137 @@
import { Injectable } from '@angular/core';
import { RoomService } from './room.service';
import { WsChatService } from 'src/app/services/chat/ws-chat.service';
import { MessageService } from 'src/app/services/chat/message.service'
import { SessionStore } from 'src/app/store/session.service';
import { capitalizeTxt } from 'src/plugin/text'
import { Rooms, Update as room } from 'src/app/models/chatMethod';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class WsChatMethodsService {
dm: {[key: string]: RoomService} = {}
group: {[key: string]: RoomService} = {}
loadingWholeList = false
dmCount = 0;
groupCount = 0;
constructor(
private WsChatService: WsChatService,
private storage: Storage
) {
(async()=>{
await this.getAllRooms();
this.subscribeToRoom()
})()
}
async getAllRooms () {
this.loadingWholeList = true
const rooms = await this.WsChatService.getRooms();
// console.log("ROOMS" + JSON.stringify(rooms))
rooms.result.update.forEach((roomData: room) => {
let room:RoomService;
//console.log(roomData);
room = new RoomService(this.WsChatService, new MessageService(), this.storage)
room.setData({
customFields: roomData.customFields,
id: this.getRoomId(roomData),
name: this.getRoomName(roomData),
t: roomData.t,
lastMessage: this.getRoomLastMessage(roomData),
_updatedAt: new Date(roomData._updatedAt['$date'])
})
room.receiveMessage()
let roomId = this.getRoomId(roomData)
if(this.isIndividual(roomData)) {
this.dm[roomId] = room
this.dmCount++
} else {
this.group[roomId] = room
this.groupCount++
}
});
this.loadingWholeList = false
}
subscribeToRoom() {
for (const id in this.dm) {
this.WsChatService.streamRoomMessages(id).then((subscription)=>{
console.log('streamRoomMessages', subscription)
})
}
for (const id in this.group) {
this.WsChatService.streamRoomMessages(id).then((subscription)=>{
console.log('streamRoomMessages', subscription)
})
}
this.WsChatService.streamNotifyLogged().then((subscription=>{
console.log('streamRoomMessages', subscription)
}))
}
getDmRoom(id): RoomService {
try {
return this.dm[id]
} catch(e) {}
}
getGroupRoom(id): RoomService {
try {
return this.group[id]
} catch(e) {}
}
getRoomName(roomData: room) {
if(this.isIndividual(roomData)) {
const names: String[] = roomData.usernames
const roomName = names.filter((name)=>{
return name != SessionStore.user.RochetChatUser
})[0]
const firstName = capitalizeTxt(roomName.split('.')[0])
const lastName = capitalizeTxt(roomName.split('.')[1])
return firstName + ' ' + lastName
} else {
return roomData.fname
}
}
getRoomId(roomData:room) {
return roomData._id
}
getRoomLastMessage(roomData: room) {
return roomData.lastMessage
}
private isIndividual(roomData: room) {
return !roomData.fname
}
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { WsChatService } from './ws-chat.service';
describe('WsChatService', () => {
let service: WsChatService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(WsChatService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
+424
View File
@@ -0,0 +1,424 @@
import { Injectable } from '@angular/core';
import { v4 as uuidv4 } from 'uuid'
import { wsCallbacksParams, msgQueue, send } from 'src/app/models/rochet-chat-cliente-service'
import { deepFind } from 'src/plugin/deep'
import { environment } from 'src/environments/environment';
import { SessionStore } from 'src/app/store/session.service';
import { chatHistory, Rooms } from 'src/app/models/chatMethod';
@Injectable({
providedIn: 'root'
})
export class WsChatService {
isLogin = false;
loginResponse = {}
constructor() {}
connect() {
// dont connect if is already connected
if(this.ws.connected == true) {
return false
}
this.ws.connect();
const message = {
msg: "connect",
version: "1",
support: ["1"]
}
this.ws.send({message, loginRequired: false})
this.ws.send({message:{msg:"pong"}, loginRequired: false})
this.ws.registerCallback({
type:'Onmessage',
key: this.constructor.name+'ping/pong',
funx:(message: any) => {
if(message.msg == "ping") {
this.ws.send({message:{msg:"pong"}, loginRequired: false})
}
}
})
}
login() {
// dont login if is already login
if(this.isLogin == true) {
return new Promise((resolve, reject)=>{
resolve(this.loginResponse)
})
}
const requestId = uuidv4()
const message = {
msg: "method",
method: "login",
id: requestId,
params: [
{
user: { username: SessionStore.user.RochetChatUser },
password: SessionStore.user.Password
}
]
}
this.ws.send({message, requestId, loginRequired: false})
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId ) { // same request send
if(message.result) {
if(message.result.token) {
this.isLogin = true
this.loginResponse = message
this.ws.wsMsgQueue()
resolve(message)
}
} else {
this.isLogin = false
reject(message)
}
reject(message)
return true
}
}})
});
}
getRooms(roomOlder = 1480377601) {
const requestId = uuidv4()
const message = {
"msg": "method",
"method": "rooms/get",
"id": requestId,
"params": [ { "$date": 1480377601 } ]
}
this.ws.send({message, requestId})
return new Promise<Rooms>((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId) { // same request send
resolve(message)
return true
}
}})
});
}
logout() {
this.isLogin = false
this.ws.connected = false
}
// send message to room
send(roomId, msg) {
const requestId = uuidv4()
var message = {
msg: "method",
method: "sendMessage",
id: requestId,
params: [{
_id: uuidv4(),
rid: roomId,
msg: msg
}]
}
this.ws.send({message, requestId});
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send
resolve(message)
return true
}
}})
});
}
joinRoom(){}
deleteMessage() {}
createRoom() {}
loadHistory(roomId, limit: number = 50) {
const requestId = uuidv4()
const message = {
msg: "method",
method: "loadHistory",
id: requestId,
params: [
roomId,
null,
limit,
{
"$date": 1480377601
}
]
}
this.ws.send({message, requestId})
return new Promise<chatHistory>((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
// console.log(message)
if(message.id == requestId ) { // same request send
resolve(message)
return true
}
}})
});
}
setStatus(status: 'online' | 'busy' | 'away' | 'offline') {
const requestId = uuidv4()
const message = {
msg: "method",
method: `UserPresence:setDefaultStatus`,
id: requestId,
params: [ status ]
}
this.ws.send({message, requestId})
}
subscribeNotifyRoom(roomId : string) {
const requestId = uuidv4()
var message = {
"msg": "sub",
"id": requestId,
"name": "stream-notify-room",
"params":[
`${roomId}/event`,
false
]
}
this.ws.send({message, requestId});
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.msg == 'ready' || deepFind(message, 'subs.0') == requestId) { // same request send
resolve(message)
return true
}
}})
});
}
receiveLiveMessageFromRoom(roomId, funx: Function) {
this.ws.registerCallback({
type:'Onmessage',
funx:(message)=>{
if(message.msg =='changed' && message.collection == 'stream-room-messages') {
if(message.fields.args[0].rid == roomId) {
funx(message)
}
}
}
})
}
streamRoomMessages(roomId : string) {
const requestId = uuidv4()
const message = {
"msg": "sub",
"id": requestId,
"name": "stream-room-messages",
"params":[
`${roomId}`,
false
]
}
this.ws.send({message, requestId});
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId) { // same request send
resolve(message)
return true
}
}})
});
}
streamNotifyLogged() {
alert('HERE')
const requestId = uuidv4()
const message = {
"msg": "sub",
"id": requestId,
"name": "stream-notify-logged",
"params":[
"user-status",
false
]
}
this.ws.send({message, requestId});
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId) { // same request send
resolve(message)
return true
}
}})
});
}
streamNotifyRoom(roomId : string) {
const requestId = uuidv4()
let message = {
"msg": "method",
"method": "stream-notify-room",
"id": requestId,
"params": [
`null/typing`,
"paulo.pinto",
true
]
};
this.ws.send({message, requestId})
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send
resolve('')
return true
}
}})
});
}
registerCallback(data:wsCallbacksParams) {
return this.ws.registerCallback(data)
}
// socket class ==================================================================
private socket!: WebSocket;
private wsMsgQueue : {[key: string]: msgQueue} = {}
private wsCallbacks: {[key: string]: wsCallbacksParams} = {}
private ws = {
connected: false,
registerCallback:(params: wsCallbacksParams) => {
let id = params.requestId || params.key || uuidv4()
this.wsCallbacks[id] = params
return id
},
connect:()=> {
this.socket = new WebSocket(environment.apiWsChatUrl);
// bind function
this.socket.onopen = this.ws.onopen;
this.socket.onmessage = this.ws.onmessage;
this.socket.onclose = this.ws.onclose;
this.socket.onerror = this.ws.onerror;
},
onopen:()=> {
this.ws.connected = true
console.log('================== welcome to socket server =====================')
this.ws.wsMsgQueue()
},
wsMsgQueue:()=> {
for (const [key, item] of Object.entries(this.wsMsgQueue)) {
if(item.loginRequired == true && this.isLogin == true) {
// console.log('run msgQueue ',index)
this.ws.send(item);
delete this.wsMsgQueue[key]
} else if(item.loginRequired == false) {
// console.log('run msgQueue ',index)
this.ws.send(item);
delete this.wsMsgQueue[key]
}
}
},
send: ({message, requestId = uuidv4(), loginRequired = true}:send) => {
if (this.ws.connected == false || loginRequired == true && this.isLogin == false) { // save data to send when back online
// console.log('save msgQueue this.ws.connected == false || loginRequired == true && this.isLogin == false',this.ws.connected, loginRequired, this.isLogin)
this.wsMsgQueue[requestId] = {message, requestId, loginRequired}
} else {
let messageStr = JSON.stringify(message)
this.socket.send(messageStr)
}
return requestId
},
onmessage:(event: any)=> {
const data = JSON.parse(event.data)
for (const [key, value] of Object.entries(this.wsCallbacks)) {
if(value.type== 'Onmessage') {
const dontRepeat = value.funx(data)
if(dontRepeat) {
delete this.wsCallbacks[key]
}
}
}
},
onclose:(event: any)=> {
this.ws.connected = false
this.isLogin = false
this.connect()
this.login()
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
},
onerror: (event: any) => {
console.log(`[error] ${event.message}`);
}
}}