merge developer

This commit is contained in:
Eudes Inácio
2022-01-31 05:50:11 +01:00
21 changed files with 730 additions and 284 deletions
+206
View File
@@ -167,3 +167,209 @@ export interface chatHistory {
unreadNotLoaded: number;
};
}
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 {
customFields:any;
_id: string;
rid: string;
msg: string;
ts: Ts;
u: U;
t: string;
_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;
};
}
export interface chatUser {
_id: string;
createdAt: Date;
emails: {
address: string;
verified: boolean;
}
type: string;
status: string;
active: boolean;
_updatedAt: Date;
roles: string[];
name: string;
lastLogin: Date;
statusConnection: string;
utcOffset: number;
username: string;
__rooms: string[];
requirePasswordChange?: boolean;
settings: {
preferences: {
language: string;
};
};
nickname: string;
statusText: string;
banners: any;
statusDefault: string;
language: string;
avatarOrigin: string;
avatarETag?: any;
}
@@ -4,6 +4,7 @@ export interface wsCallbacksParams {
runOnces?: boolean
requestId?: string
key?: string
order?: number
}
@@ -39,7 +39,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
showLoader: boolean;
isGroupCreated:boolean;
loggedUser: any;
messages:any;
room:any;
roomName:any;
@@ -101,7 +100,8 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory();
this.wsChatMethodsService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked;
this.wsChatMethodsService.openRoom(this.roomId)
setTimeout(()=>{
this.scrollToBottomClicked()
}, 50)
@@ -613,7 +613,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
chatmsgArray.push(msgChat)
});
this.messages = chatmsgArray;
// this.messages = chatmsgArray;
console.log('GROUP CHAT MSG FROM DB', chatmsgArray)
})
}
@@ -672,7 +672,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
//this.loadMessages()
let msgOnly = res['messages'].filter(data => data.t != 'au');
//this.messages = msgOnly.reverse();
console.log('MOBILE MSG ROCKET',this.messages);
// console.log('MOBILE MSG ROCKET',this.messages);
this.transformDataMSG(msgOnly.reverse());
this.getRoomMessageDB(this.roomId);
// Reconnect in one second
@@ -29,7 +29,7 @@
</ion-refresher>
<div class="main-content">
<ion-virtual-scroll [items]="users | filter:textSearch: 'name'" approxItemHeight="70px" [headerFn]="separateLetter">
<ion-virtual-scroll [items]="WsChatMethodsService.users | filter:textSearch: 'name'" approxItemHeight="70px" [headerFn]="separateLetter">
<div class="item-divider" *virtualHeader="let header">
<ion-label>{{header}}</ion-label>
@@ -6,6 +6,7 @@ import { ChatService } from 'src/app/services/chat.service';
import { GroupMessagesPage } from '../../group-messages/group-messages.page';
import { MessagesPage } from '../messages.page';
import { ThemeService } from 'src/app/services/theme.service'
import { WsChatMethodsService} from 'src/app/services/chat/ws-chat-methods.service'
@Component({
selector: 'app-contacts',
@@ -29,7 +30,8 @@ export class ContactsPage implements OnInit {
private http: HttpClient,
private chatService: ChatService,
private authService: AuthService,
public ThemeService: ThemeService
public ThemeService: ThemeService,
public WsChatMethodsService: WsChatMethodsService
)
{
this.loggedUser = authService.ValidatedUserChat['data'];
+6 -29
View File
@@ -49,8 +49,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
canvas: any
ctx: any
loggedUser: any;
message = '';
messages: any;
userPresence = '';
dmUsers: any;
roomId: string;
@@ -114,7 +112,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory()
this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked
this.wsChatMethodsService.openRoom(this.roomId)
setTimeout(()=>{
this.scrollToBottomClicked()
}, 150)
@@ -348,31 +347,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
sendMessage() {
let body = {
"message":
{
"rid": this.roomId, "msg": this.message
}
}
this.chatService.sendMessage(body).subscribe(res => {
//this.loadMessages();
this.scrollingOnce = true;
});
this.message = "";
this.wsChatMethodsService.getDmRoom(this.roomId).send()
}
loadMessages() {
this.showLoader = true;
const roomId = this.roomId;
this.chatService.getRoomMessages(this.roomId).subscribe(res => {
console.log(res);
this.messages = res['messages'].reverse();
this.chatMessageStore.add(roomId, this.messages)
console.log(this.messages);
this.showLoader = false;
})
}
viewDocument(file: any, url?: string) {
@@ -575,7 +553,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.fileService.addDocGestaoDocumentalToChat(this.roomId);
//this.addDocGestaoDocumental();
}
this.loadMessages();
});
}
@@ -641,7 +619,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
chatmsgArray.push(msgChat)
});
this.messages = chatmsgArray.reverse();
console.log('CHAT MSG FROM DB', chatmsgArray)
})
}
@@ -716,8 +694,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
//showMessage(response.statusText);
//this.loadMessages()
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.messages = res['messages'].reverse();
this.chatMessageStore.add(roomId, this.messages)
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AppProcessStatusService } from './app-process-status.service';
describe('AppProcessStatusService', () => {
let service: AppProcessStatusService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AppProcessStatusService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,25 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AppProcessStatusService {
status: 'resume' | 'pause' = 'resume'
constructor() {
this.events()
}
private events() {
document.addEventListener('pause', () => {
// console.log('App going to background');
this.status = 'pause'
});
document.addEventListener('resume', () => {
// console.log('App going to background');
this.status = 'resume'
});
}
}
+1 -3
View File
@@ -117,7 +117,6 @@ export class AuthService {
if(responseChat) {
setTimeout(()=>{
console.log('login', SessionStore.user.RochetChatUser, SessionStore.user.Password)
this.WsChatService.connect();
this.WsChatService.login().then((message) => {
@@ -133,9 +132,8 @@ export class AuthService {
this.ValidatedUserChat = responseChat;
localStorage.setItem('userChat', JSON.stringify(responseChat));
this.storageService.store(AuthConnstants.AUTH, responseChat);
return true;
}
else{
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ChatStorageService } from './chat-storage.service';
describe('ChatStorageService', () => {
let service: ChatStorageService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ChatStorageService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,170 @@
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class ChatStorageService {
constructor(
private storage: Storage,
) { }
/**
* @description delete message in the DB. get all messages, delete then corresponding message and update the store
* @param id message ID
*/
private deleteMessageFromDb(messageId, roomId) {
this.storage.get('chatmsg' + roomId).then((messages: any = []) => {
messages.forEach((message, index) => {
if(message._id == messageId) {
messages.splice(index, 1)
}
})
this.storage.set('chatmsg' + roomId, messages).then((value) => {
console.log('MSG SAVED ON STORAGE', value)
});
})
}
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)
});
}) */
}
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)
// });
}
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)
// });
// });
}
}
+1 -1
View File
@@ -42,7 +42,7 @@ export class MessageService {
if (this.file) {
if (this.file.guid) {
this.storage.get(this.file.guid).then((image) => {
console.log('IMAGE FROM STORAGE', image)
// console.log('IMAGE FROM STORAGE', image)
this.file.image_url = image
});
}
+88 -181
View File
@@ -12,6 +12,8 @@ import { NativeNotificationService } from 'src/app/services/native-notification.
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';
@Injectable({
providedIn: 'root'
})
@@ -41,6 +43,14 @@ export class RoomService {
scrollDown = () => { }
/**
* @description get user list from ws-chat-methods.service
* @returns chatUser[]
*/
getAllUsers = (): chatUser[] => {
return []
}
constructor(
public WsChatService: WsChatService,
private MessageService: MessageService,
@@ -74,9 +84,8 @@ export class RoomService {
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)
const message = this.prepareMessage(ChatMessage)
this.lastMessage = message
if (message.t == 'r') { this.name = message.msg }
@@ -130,29 +139,61 @@ export class RoomService {
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)
}
})
const DeletedMessageId = ChatMessage.fields.args[0]._id;
console.log(DeletedMessageId);
this.deleteMessage(DeletedMessageId)
}
)
this.WsChatService.registerCallback
}
/**
* @description delete message in the view
* @param id message ID
*/
deleteMessage(id) {
this.messages.forEach((message, index) => {
if(message._id == id) {
this.messages.splice(index, 1)
this.deleteMessageFromDb(id)
//Get previous last message from room
const previousLastMessage = this.messages.slice(-1)[0];
this.lastMessage = previousLastMessage;
this.calDateDuration(previousLastMessage._updatedAt)
}
})
}
/**
* @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 = []) => {
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
*/
send() {
this.WsChatService.send(this.id, this.message)
this.message= ''
@@ -198,46 +239,23 @@ export class RoomService {
}, 3000)
}
private setTypingOff() {
this.typing('')
}
roomLeave() {
this.setTypingOff()
}
open() {
// this.typing(this.message)
}
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);
@@ -247,32 +265,6 @@ export class RoomService {
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) {
@@ -284,9 +276,7 @@ export class RoomService {
let localMessages = []
messages.forEach(message => {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage)
wewMessage.setData(message)
const wewMessage = this.prepareMessage(message)
localMessages.push(wewMessage)
});
@@ -297,12 +287,11 @@ export class RoomService {
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)
const wewMessage = this.prepareMessage(message)
localMessages.push(wewMessage)
});
@@ -315,28 +304,6 @@ export class RoomService {
})
/* 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)
@@ -345,6 +312,15 @@ export class RoomService {
}
prepareMessage(message) {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage)
wewMessage.setData(message)
return wewMessage
}
updateMeessage(messageID, imgbase64) {
}
@@ -354,75 +330,6 @@ export class RoomService {
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() { }
@@ -437,7 +344,7 @@ export class RoomService {
console.log('FIX UPDATE ', message.result)
message.result._updatedAt = message.result._updatedAt['$date']
} else {
console.log('FIX UPDATE 11', message)
// console.log('FIX UPDATE 11', message)
message._updatedAt = message._updatedAt['$date']
}
return message
+157 -43
View File
@@ -8,8 +8,10 @@ import { Rooms, Update as room } from 'src/app/models/chatMethod';
import { Storage } from '@ionic/storage';
import { Platform } from '@ionic/angular';
import { SqliteService } from 'src/app/services/sqlite.service';
import { ChatService } from 'src/app/services/chat.service';
import { NativeNotificationService } from 'src/app/services/native-notification.service';
import { SortService } from '../functions/sort.service';
import { chatUser } from 'src/app/models/chatMethod';
@Injectable({
providedIn: 'root'
@@ -28,18 +30,28 @@ export class WsChatMethodsService {
dmCount = 0;
groupCount = 0;
currentRoom = null
users: chatUser[] = []
constructor(
private WsChatService: WsChatService,
private storage: Storage,
private platform: Platform,
private sqlservice: SqliteService,
private NativeNotificationService: NativeNotificationService,
private sortService: SortService
private sortService: SortService,
private ChatService: ChatService
) {
(async()=>{
await this.getAllRooms();
this.subscribeToRoom()
//
await this.getUser()
this.getUserStatus()
})()
}
@@ -51,6 +63,27 @@ export class WsChatMethodsService {
});
})
};
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 = 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()
}
}
}
async getAllRooms () {
this.loadingWholeList = true
@@ -68,82 +101,59 @@ export class WsChatMethodsService {
if(message.fields.args[0].rid) {
setTimeout(()=>{
console.log('sort this._dm', this._dm)
this._dm = this.sortService.sortDate(this._dm,'_updatedAt').reverse()
this._group = this.sortService.sortDate(this._group,'_updatedAt').reverse()
this.sortRoomList()
}, 100)
}
}
if(message.msg =='changed' && message.collection == "stream-notify-room") {
if(message.fields.eventName.includes('deleteMessage')){
setTimeout(()=>{
console.log('sort this._dm', this._dm)
this._dm = this.sortService.sortDate(this._dm,'_updatedAt').reverse()
this._group = this.sortService.sortDate(this._group,'_updatedAt').reverse()
this.sortRoomList()
}, 100)
}
}
}
})
await rooms.result.update.forEach( async (roomData: room) => {
await this.prepareRoom(roomData);
});
this._dm = this.sortService.sortDate(this._dm,'_updatedAt').reverse()
this._group = this.sortService.sortDate(this._group,'_updatedAt').reverse()
this.sortRoomList()
this.loadingWholeList = false
}
sortRoomList() {
this._dm = this.sortService.sortDate(this._dm,'_updatedAt').reverse()
this._group = this.sortService.sortDate(this._group,'_updatedAt').reverse()
}
subscribeToRoom() {
for (const id in this.dm) {
this.WsChatService.streamRoomMessages(id).then((subscription)=>{
console.log('streamRoomMessages', subscription)
})
this.WsChatService.subStreamNotifyRoom(id, 'typing', false)
this.WsChatService.streamNotifyRoomDeleteMessage(id).then((subscription)=>{
console.log('streamNotifyRoomDeleteMessage', subscription);
})
this.defaultSubtribe(id)
}
for (const id in this.group) {
this.WsChatService.streamRoomMessages(id).then((subscription)=>{
console.log('streamRoomMessages', subscription)
})
this.WsChatService.subStreamNotifyRoom(id, 'typing', false)
this.WsChatService.streamNotifyRoomDeleteMessage(id).then((subscription)=>{
console.log('streamNotifyRoomDeleteMessage', subscription);
})
this.defaultSubtribe(id)
}
this.WsChatService.streamNotifyLogged().then((subscription=>{
console.log('streamRoomMessages', subscription)
}))
}
/**
* @description when a new room is create, needs to subtribe in order to receive updates
* @param id
* @param roomData
*/
subscribeToRoomUpdate(id, roomData) {
this.WsChatService.streamRoomMessages(id).then((subscription)=> {
console.log('streamRoomMessages', subscription)
})
this.WsChatService.streamRoomMessages(id).then((subscription) => {
console.log('streamRoomMessages', subscription)
})
this.WsChatService.streamNotifyLogged().then((subscription=> {
console.log('streamRoomMessages', subscription)
}))
this.WsChatService.streamNotifyRoomDeleteMessage(id).then((subscription)=>{
console.log('streamNotifyRoomDeleteMessage', subscription);
})
this.defaultSubtribe(id)
this.prepareRoom(roomData);
@@ -151,6 +161,27 @@ export class WsChatMethodsService {
}
/**
* @deprecated things a room need to subscribe on
* @param id room id
*/
private defaultSubtribe(id: any) {
this.WsChatService.streamRoomMessages(id).then((subscription)=>{
console.log('streamRoomMessages', subscription)
})
this.WsChatService.subStreamNotifyRoom(id, 'typing', false)
this.WsChatService.streamNotifyRoomDeleteMessage(id).then((subscription)=>{
console.log('streamNotifyRoomDeleteMessage', subscription);
})
}
/**
* @description create a representation of an room in these instance this.dm, this.group ...
* @param roomData
*/
prepareRoom(roomData) {
let room:RoomService;
@@ -166,6 +197,7 @@ export class WsChatMethodsService {
})
room.receiveMessage()
room.getAllUsers = this.getUsers
room.receiveMessageDelete();
let roomId = this.getRoomId(roomData)
@@ -181,6 +213,64 @@ export class WsChatMethodsService {
}
}
getReceptorName(roomData) {
try {
return roomData.usernames.find((e)=> e != SessionStore.user.RochetChatUser)
} catch(e) {
return '*'
}
}
/**
* @description update user status. this method is called once only
* @param id user ID
*/
private getUserStatus(id?:string) {
this.WsChatService.getUserStatus((d) => {
const username = d.fields.args[0][1]
const statusNum = d.fields.args[0][2]
const statusText = this.statusNumberToText(statusNum)
const user = this.getUserByName(username)
if(user) {
user.status = statusText
}
})
}
getUserByName(username) {
return this.users.find((user)=> user.username == username)
}
/**
* @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"
}
}
deleteMessage(id?) {
return this.WsChatService.deleteMessage(id);
}
@@ -240,4 +330,28 @@ export class WsChatMethodsService {
return !roomData.fname
}
getUsers = () =>{
return this.users
}
async getUser() {
let _res = await this.ChatService.getAllUsers().toPromise()
let user = _res['users'].filter(data => data.username != SessionStore.user.RochetChatUser);
user = user.sort((a,b) => {
if(a.name < b.name) {
return -1;
}
if(a.name > b.name) {
return 1;
}
return 0;
});
this.users = user
}
}
+18 -4
View File
@@ -35,7 +35,6 @@ export class WsChatService {
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})
@@ -204,7 +203,7 @@ export class WsChatService {
});
}
hidingRoom(roomId){
hidingRoom(roomId) {
const requestId = uuidv4()
@@ -350,6 +349,19 @@ export class WsChatService {
}})
}
getUserStatus(funx:Function){
this.ws.registerCallback({
type:'Onmessage',
funx:(message)=>{
if(message.msg == 'changed' && message.collection == "stream-notify-logged") {
funx(message)
}
}
})
}
loadHistory(roomId, limit: number = 50) {
const requestId = uuidv4()
@@ -589,11 +601,11 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) {
for (const [key, item] of Object.entries(this.wsMsgQueue)) {
if(item.loginRequired == true && this.isLogin == true) {
// console.log('run msgQueue ',index)
console.log('run msgQueue ', key)
this.ws.send(item);
delete this.wsMsgQueue[key]
} else if(item.loginRequired == false) {
// console.log('run msgQueue ',index)
console.log('run msgQueue ', key)
this.ws.send(item);
delete this.wsMsgQueue[key]
}
@@ -603,6 +615,8 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) {
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)
console.log('save msgQueue', requestId)
this.wsMsgQueue[requestId] = {message, requestId, loginRequired}
} else {
let messageStr = JSON.stringify(message)
@@ -18,9 +18,9 @@ export class NativeNotificationService {
LocalNotifications.requestPermissions()
LocalNotifications.checkPermissions().then((data)=>{
console.log('success', data)
// console.log('success', data)
}).catch((data)=>{
console.log('error', data)
// console.log('error', data)
})
}
@@ -111,8 +111,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
this.getRoomInfo();
//this.scrollToBottom();
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory();
this.wsChatMethodsService.getGroupRoom(this.roomId).getMsgFromDB();
console.log('MESSAGES'+ this.wsChatMethodsService.getGroupRoom(this.roomId).messages);
// console.log('MESSAGES'+ this.wsChatMethodsService.getGroupRoom(this.roomId).messages);
this.wsChatMethodsService.openRoom(this.roomId)
this.wsChatMethodsService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked
setTimeout(()=>{
@@ -29,7 +29,7 @@
<div class="main-content">
<ion-virtual-scroll [items]="users| filter:textSearch: 'name'" approxItemHeight="70px" [headerFn]="separateLetter">
<ion-virtual-scroll [items]="WsChatMethodsService.users | filter:textSearch: 'name'" approxItemHeight="70px" [headerFn]="separateLetter">
<div class="item-divider" *virtualHeader="let header">
<ion-label>{{header}}</ion-label>
@@ -6,6 +6,7 @@ import { ChatService } from 'src/app/services/chat.service';
import { GroupMessagesPage } from '../../group-messages/group-messages.page';
import { MessagesPage } from '../messages.page';
import { ThemeService } from 'src/app/services/theme.service'
import { WsChatMethodsService} from 'src/app/services/chat/ws-chat-methods.service'
@Component({
selector: 'app-contacts',
@@ -31,7 +32,8 @@ export class ContactsPage implements OnInit {
private http: HttpClient,
private chatService: ChatService,
private authService: AuthService,
public ThemeService: ThemeService
public ThemeService: ThemeService,
public WsChatMethodsService: WsChatMethodsService
)
{
this.loggedUser = authService.ValidatedUserChat['data'];
+3 -11
View File
@@ -100,21 +100,13 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}
ngOnChanges(changes: SimpleChanges): void {
this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory()
//this.wsChatMethodsService.getDmRoom(this.roomId).getMsgFromDB()
this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked
/* console.log('DATATATA', this.wsChatMethodsService.getDmRoom(this.roomId).massages)
this.wsChatMethodsService.getDmRoom(this.roomId).massages.forEach((element) => {
console.log('DATATATA 11', element)
}) */
//this.transformData(this.wsChatMethodsService.getDmRoom(this.roomId).massages)
//this.getMessageDB()
this.wsChatMethodsService.openRoom(this.roomId)
setTimeout(() => {
this.scrollToBottomClicked()
}, 50)
}, 150)
}
+6
View File
@@ -0,0 +1,6 @@
// https://stackoverflow.com/a/68628927/14115342
const ArrayToObject = (array = [], getKey) => array.reduce((obj, cur) => {
const key = getKey(cur);
return (Object.assign(Object.assign({}, obj), { [key]: cur }));
}, {});