Merge branch 'feature/websocket' of https://bitbucket.org/equilibriumito/gabinete-digital into feature/websocket

This commit is contained in:
tiago.kayaya
2022-01-13 13:46:56 +01:00
13 changed files with 341 additions and 108 deletions
+167
View File
@@ -0,0 +1,167 @@
interface Ts {
$date: any;
}
interface U {
_id: string;
username: string;
name: string;
}
interface UpdatedAt {
$date: any;
}
interface Attachment {
ts: Date;
title_link_download: boolean;
}
export interface File {
type: string;
guid: string;
image_url: string;
subject: string;
start_date?: Date;
end_date?: Date;
venue: string;
id: string;
}
interface EditedAt {
$date: number;
}
interface EditedBy {
_id: string;
username: string;
}
interface Ts2 {
$date: number;
}
interface U2 {
_id: string;
username: string;
name: string;
}
interface UpdatedAt2 {
$date: number;
}
interface FirstUnread {
_id: string;
rid: string;
msg: string;
ts: Ts2;
u: U2;
_updatedAt: UpdatedAt2;
mentions: any[];
channels: any[];
}
export interface Message {
_id: string;
rid: string;
msg: string;
ts: Ts;
u: U;
_updatedAt: UpdatedAt;
mentions: any[];
channels: any[];
attachments: Attachment[];
file: File;
editedAt: EditedAt;
editedBy: EditedBy;
urls: any[];
}
export interface Lm {
$date: any;
}
export interface LastMessage {
_id: string;
rid: string;
msg: string;
ts: Ts;
u: U;
_updatedAt: UpdatedAt2;
mentions: any[];
channels: any[];
file: File;
attachments: Attachment[];
}
export interface CustomFields {
}
export interface Update {
_id: string;
t: string;
usernames: string[];
usersCount: number;
uids: string[];
default: boolean;
ro: boolean;
sysMes: boolean;
_updatedAt: UpdatedAt;
lm: Lm;
lastMessage: LastMessage;
name: string;
fname: string;
u: U2;
customFields: CustomFields;
}
export interface DeletedAt {
$date: any;
}
export interface Remove {
_id: string;
_deletedAt: DeletedAt;
}
export interface Result {
update: Update[];
remove: Remove[];
}
export interface Rooms {
msg: string;
id: string;
result: Result;
}
export interface ChatMessage {
msg: string;
id: string;
result: Message
}
export interface chatHistory {
msg: string;
id: string;
result: {
messages: Message[];
firstUnread: FirstUnread;
unreadNotLoaded: number;
};
}
@@ -3,6 +3,7 @@ export interface wsCallbacksParams {
funx: Function
runOnces?: boolean
requestId?: string
key?: string
}
@@ -10,4 +11,10 @@ export interface msgQueue {
message: object,
requestId: string,
loginRequired: boolean
}
export interface send {
message: object
requestId?: string
loginRequired?: boolean
}
+4 -4
View File
@@ -121,10 +121,10 @@
{{group.value.name.split('-').join(' ')}}
<ion-label>{{group.value.name.split('-').join(' ')}}</ion-label>TT
</div>
<div class="item-date" [class.item-date-active]="group.value.id ==idSelected" *ngIf="group.value.lastMessage && !group.customFields.countDownDate">{{showDateDuration(group._updatedAt)}}</div>
<div class="item-date" [class.item-date-active]="group.value.id ==idSelected" *ngIf="group.value.customFields.countDownDate">{{countDownDate(group.value.customFields.countDownDate, group.value.id)}}</div>
<!-- <div class="item-date" [class.item-date-active]="group.value.id ==idSelected" *ngIf="group.value.lastMessage && !group.customFields.countDownDate">{{group.value.duration}}</div>
<div class="item-date" [class.item-date-active]="group.value.id ==idSelected" *ngIf="group.value.customFields.countDownDate">{{countDownDate(group.value.customFields.countDownDate, group.value.id)}}</div> -->
</div>
<div *ngIf="group.value.lastMessage" class="item-description d-flex align-items-center" [class.item-description-active]="group.value.id ==idSelected">
<!-- <div *ngIf="group.value.lastMessage" class="item-description d-flex align-items-center" [class.item-description-active]="group.value.id ==idSelected">
<div class="item-message">{{group.value.lastMessage.u.name}}: {{group.lastMessage.msg}} </div>
<div class="item-files add-ellipsis" *ngIf="group.value.lastMessage.file">
<fa-icon *ngIf="group.value.lastMessage.file.type != 'application/meeting'" icon="file-alt" class="file-icon" [class.set-active-item-font-to-white]="group.value.id == idSelected"></fa-icon>
@@ -137,7 +137,7 @@
<span> Fotografia</span>
</div>
</div>
</div>
</div> -->
</div>
</div>
</ion-item-sliding>
+2
View File
@@ -42,6 +42,7 @@ export class AuthService {
this.WsChatService.connect();
this.WsChatService.login().then((message) => {
console.log('rocket chat login successfully', message)
this.WsChatService.temporaryStatus('online')
}).catch((message)=>{
console.log('rocket chat login failed', message)
})
@@ -115,6 +116,7 @@ export class AuthService {
this.WsChatService.connect();
this.WsChatService.login().then((message) => {
console.log('rocket chat login successfully', message)
this.WsChatService.temporaryStatus('online')
}).catch((message)=>{
console.log('rocket chat login failed', message)
})
+7 -4
View File
@@ -1,4 +1,6 @@
import { Injectable } from '@angular/core';
import { Message } from 'src/app/models/chatMethod';
import { chatHistory, ChatMessage, File } from 'src/app/models/chatMethod'
@Injectable({
providedIn: 'root'
@@ -13,10 +15,12 @@ export class MessageService {
u = {}
_id =''
_updatedAt = {}
file
attachments
constructor() { }
setData({channels, mentions, msg ,rid ,ts, u, _id, _updatedAt}) {
setData({channels, mentions, msg ,rid ,ts, u, _id, _updatedAt, file, attachments}:Message) {
this.channels = channels
this.mentions = mentions
this.msg = msg
@@ -25,13 +29,12 @@ export class MessageService {
this.u = u
this._id = _id
this._updatedAt = _updatedAt
this.file = file
this.attachments = attachments
}
delete() {}
showDateDuration() {}
}
+20 -17
View File
@@ -3,6 +3,8 @@ 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'
@Injectable({
providedIn: 'root'
})
@@ -18,6 +20,7 @@ export class RoomService {
private hasLoadHistory = false
duration = ''
private ToastService = ToastsService
constructor(
public WsChatService: WsChatService,
@@ -25,7 +28,6 @@ export class RoomService {
) {}
setData({id, name, lastMessage, _updatedAt}) {
this.id = id
this.name = name
this.lastMessage = lastMessage
@@ -37,15 +39,14 @@ export class RoomService {
receiveMessage() {
this.WsChatService.receiveLiveMessageFromRoom(
this.id,
this.constructor.name+this.id,
(Chatmessage) => {
(ChatMessage:ChatMessage) => {
Chatmessage = this.fix_updatedAt(Chatmessage)
ChatMessage = this.fix_updatedAt(ChatMessage)
const message = new MessageService()
message.setData(Chatmessage.result)
message.setData(ChatMessage.result)
this.massages.push(message)
this.calDateDuration(Chatmessage.result._updatedAt)
this.calDateDuration(ChatMessage.result._updatedAt)
this.ToastService.presentToast('nova mensagem')
}
)
}
@@ -59,15 +60,15 @@ export class RoomService {
if(this.hasLoadHistory){ return false}
this.WsChatService.loadHistory(this.id, limit).then((message:any) => {
console.log('loadHistory', message)
this.WsChatService.loadHistory(this.id, limit).then((chatHistory:chatHistory) => {
console.log('loadHistory', chatHistory)
message.result.messages.reverse().forEach(element => {
console.log('element', element)
element = this.fix_updatedAt(element)
const message = new MessageService()
message.setData(element)
this.massages.push(message)
chatHistory.result.messages.reverse().forEach(message => {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService()
wewMessage.setData(message)
this.massages.push(wewMessage)
});
})
@@ -75,8 +76,6 @@ export class RoomService {
this.hasLoadHistory = true
}
create() {}
deleteMessage(msgId) {}
ReactToMessage() {}
private calDateDuration(date = null) {
@@ -93,4 +92,8 @@ export class RoomService {
return message
}
// to add
countDownDate(){}
}
@@ -3,7 +3,8 @@ 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';
@Injectable({
providedIn: 'root'
@@ -34,11 +35,11 @@ export class WsChatMethodsService {
async getAllRooms () {
this.loadingWholeList = true
const rooms: any = await this.WsChatService.getRooms();
const rooms = await this.WsChatService.getRooms();
console.log("ROOMS" + rooms)
// console.log("ROOMS" + JSON.stringify(rooms))
rooms.result.update.forEach((roomData:any) => {
rooms.result.update.forEach((roomData: room) => {
let room:RoomService;
console.log(roomData);
@@ -64,8 +65,11 @@ export class WsChatMethodsService {
this.groupCount++
}
});
console.log('this.group', this.group)
this.loadingWholeList = false
}
@@ -91,29 +95,31 @@ export class WsChatMethodsService {
}
}
getRoomName(roomData) {
getRoomName(roomData: room) {
if(this.isIndividual(roomData)) {
const names: String[] = roomData.usernames
const roomName = names.filter((name)=>{
return name != SessionStore.user.RochetChatUser
})[0]
return roomName
const firstName = capitalizeTxt(roomName.split('.')[0])
const lastName = capitalizeTxt(roomName.split('.')[1])
return firstName + ' ' + lastName
} else {
return roomData.fname
}
}
getRoomId(roomData) {
getRoomId(roomData:room) {
return roomData.lastMessage.rid
}
getRoomLastMessage(roomData) {
getRoomLastMessage(roomData: room) {
return roomData.lastMessage
}
private isIndividual(roomData) {
return roomData.t == "d";
private isIndividual(roomData: room) {
return !roomData.fname
}
}
+96 -68
View File
@@ -1,9 +1,10 @@
import { Injectable } from '@angular/core';
import { v4 as uuidv4 } from 'uuid'
import { wsCallbacksParams, msgQueue } from 'src/app/models/rochet-chat-cliente-service'
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'
@@ -15,23 +16,34 @@ export class WsChatService {
constructor() {}
connect() {
this.ws.connect();
const connectMessage = {
const message = {
msg: "connect",
version: "1",
support: ["1"]
}
this.ws.send(connectMessage, 'connect', false)
this.ws.send({msg:"pong"},'recoonect', false)
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() {
const requestId = uuidv4()
const loginRequest = {
const message = {
msg: "method",
method: "login",
id: requestId,
@@ -42,16 +54,14 @@ export class WsChatService {
}
]
}
this.ws.send(loginRequest, requestId, false)
this.ws.send({message, requestId, loginRequired: false})
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', requestId, funx:(message)=>{
console.log('message login', message)
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId ) { // same request send
console.log('message login', message)
if(message.result.token) {
console.log('this.isLogin = true')
this.isLogin = true
this.ws.wsMsgQueue()
@@ -75,17 +85,17 @@ export class WsChatService {
const requestId = uuidv4()
const request = {
const message = {
"msg": "method",
"method": "rooms/get",
"id": requestId,
"params": [ { "$date": 1480377601 } ]
}
this.ws.send(request, requestId, true)
this.ws.send({message, requestId})
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', requestId, funx:(message)=>{
return new Promise<Rooms>((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId) { // same request send
resolve(message)
return true
@@ -94,27 +104,31 @@ export class WsChatService {
});
}
logout() {}
send(roomId, message) {
logout() {
this.isLogin = false
this.ws.connected = false
}
// send message to room
send(roomId, msg) {
const requestId = uuidv4()
var request = {
var message = {
msg: "method",
method: "sendMessage",
id: requestId,
params: [{
_id: uuidv4(),
rid: roomId,
msg: message
msg: msg
}]
}
this.ws.send(request, requestId, true);
this.ws.send({message, requestId});
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', requestId, funx:(message)=>{
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send
resolve(message)
return true
@@ -133,7 +147,7 @@ export class WsChatService {
const requestId = uuidv4()
const request = {
const message = {
msg: "method",
method: "loadHistory",
id: requestId,
@@ -147,10 +161,10 @@ export class WsChatService {
]
}
this.ws.send(request, requestId, true)
this.ws.send({message, requestId})
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', requestId, funx:(message)=>{
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)
@@ -160,11 +174,28 @@ export class WsChatService {
});
}
temporaryStatus(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 subscribeRequest = {
var message = {
"msg": "sub",
"id": requestId,
"name": "stream-notify-room",
@@ -174,10 +205,10 @@ export class WsChatService {
]
}
this.ws.send(subscribeRequest, requestId, true);
this.ws.send({message, requestId});
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', requestId, funx:(message)=>{
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.msg == 'ready' || deepFind(message, 'subs.0') == requestId) { // same request send
resolve(message)
return true
@@ -192,16 +223,17 @@ export class WsChatService {
* @param key
* @param funx
*/
receiveLiveMessageFromRoom(roomId =')(', key, funx: Function) {
receiveLiveMessageFromRoom(roomId, funx: Function) {
this.ws.registerCallback({
type:'Onmessage',
requestId: key,
funx:(message)=>{
if(message.msg =='result') {
if(message.result.msg) {
if(message.result.rid == roomId) {
funx(message)
if(message.result) {
if(message.result.msg) {
if(message.result.rid == roomId) {
funx(message)
}
}
}
}
@@ -214,7 +246,7 @@ export class WsChatService {
const requestId = uuidv4()
const request = {
const message = {
"msg": "sub",
"id": requestId,
"name": "stream-room-messages",
@@ -224,10 +256,10 @@ export class WsChatService {
]
}
this.ws.send(request, requestId, true);
this.ws.send({message, requestId});
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', requestId, funx:(message)=>{
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.msg == 'ready' || deepFind(message, 'subs.0') == requestId) { // same request send
resolve(message)
return true
@@ -240,7 +272,7 @@ export class WsChatService {
const requestId = uuidv4()
let streamNotifyObj = {
let message = {
"msg": "method",
"method": "stream-notify-room",
"id": requestId,
@@ -251,10 +283,10 @@ export class WsChatService {
]
};
this.ws.send(streamNotifyObj, requestId, true)
this.ws.send({message, requestId})
return new Promise((resolve, reject) => {
this.ws.registerCallback({type:'Onmessage', requestId, funx:(message)=>{
this.ws.registerCallback({type:'Onmessage', funx:(message)=>{
if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send
resolve('')
return true
@@ -269,24 +301,18 @@ export class WsChatService {
}
// socket class ==================================================================
private socket!: WebSocket;
private wsUrl = ''
private wsMsgQueue : msgQueue[] = []
private socket!: WebSocket;
private wsMsgQueue : {[key: string]: msgQueue} = {}
private wsCallbacks: {[key: string]: wsCallbacksParams} = {}
private ws = {
connected: false,
registerCallback:(params: wsCallbacksParams) => {
if(!params.requestId) {
params.requestId = uuidv4()
}
this.wsCallbacks[params.requestId] = {
type: params.type,
funx: params.funx
}
let id = params.requestId || params.key || uuidv4()
this.wsCallbacks[id] = params
return id
},
connect:()=> {
this.socket = new WebSocket(environment.apiWsChatUrl);
@@ -303,24 +329,25 @@ export class WsChatService {
this.ws.wsMsgQueue()
},
wsMsgQueue:()=> {
this.wsMsgQueue.forEach((item, index, object) => {
if(item.loginRequired == true && this.isLogin == true) {
console.log('run msgQueue ',index)
this.ws.send(item.message, item.requestId, item.loginRequired);
delete this.wsMsgQueue[item.requestId]
} else if(item.loginRequired == false) {
console.log('run msgQueue ',index)
this.ws.send(item.message, item.requestId, item.loginRequired);
delete this.wsMsgQueue[item.requestId]
}
})
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: object, requestId = uuidv4(), loginRequired) => {
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.push({message, requestId, loginRequired})
// 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)
@@ -329,8 +356,8 @@ export class WsChatService {
},
onmessage:(event: any)=> {
// if(this.ws.connected == false) { return true }
const data = JSON.parse(event.data)
// console.log('event.data', data)
for (const [key, value] of Object.entries(this.wsCallbacks)) {
if(value.type== 'Onmessage') {
@@ -347,11 +374,12 @@ export class WsChatService {
},
onclose:(event: any)=> {
this.ws.connected = false
this.isLogin = false
this.connect()
this.login()
this.ws.connected = false
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
},
+4 -3
View File
@@ -10,9 +10,7 @@ export class ToastService {
constructor(
public toastController: ToastController,
private animationController: AnimationController,
private modalController: ModalController,
) { }
) { }
ngOnInit() {}
@@ -230,3 +228,6 @@ export class ToastService {
}
}
export const ToastsService = new ToastService(new ToastController())
@@ -133,7 +133,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
ev.target.complete();
}
scrollToBottom(): void {
scrollToBottom = () => {
try {
if(this.scrollingOnce){
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
+9
View File
@@ -66,6 +66,15 @@
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script type="module" src="./assets/js/index.js"></script>
<script>
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
</script>
</head>
<body class='gov'>
+1 -1
View File
@@ -14,5 +14,5 @@ function deepFind(obj, path) {
}
module.exports = {
deepFind: deepFind,
deepFind: deepFind,
};
+7
View File
@@ -0,0 +1,7 @@
function capitalizeTxt(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}
module.exports = {
capitalizeTxt: capitalizeTxt
}