diff --git a/src/app/home/home.page.ts b/src/app/home/home.page.ts index 059d8eeb4..17ba9ebc9 100644 --- a/src/app/home/home.page.ts +++ b/src/app/home/home.page.ts @@ -94,34 +94,7 @@ export class HomePage implements OnInit { private sqliteservice: SqliteService, private RouteService: RouteService, private RocketChatClientService: RocketChatClientService) { - - /* this.RocketChatClientService.loadHistory('fsMwcNdufWvdnChj7ya9nF9cX2HizxxWAM', 10).then((message)=>{ - console.log('loadHistory', message) - }) - - - this.RocketChatClientService.getRooms().then((rooms: any)=>{ - console.log('rooms', rooms) - - rooms.result.update.forEach((room:any) => { - console.log('room', room) - this.RocketChatClientService.subscribe(room.lastMessage.rid).then((subscription)=>{ - console.log('subscription', subscription) - }) - }); - }); - - - this.RocketChatClientService.receiveLiveMessageFromRoom( - 'fsMwcNdufWvdnChj7ya9nF9cX2HizxxWAM', - this.constructor.name, - (Chatmessage)=>{ - console.log('chat', Chatmessage) - } - ) */ - - - window['jj'] = ()=>{ + window['jj'] = ()=> { //send message // roomId // Message //this.RocketChatClientService.send('fsMwcNdufWvdnChj7ya9nF9cX2HizxxWAM', 'Mensagem enviada programaticamente.'+ new Date().toISOString()) } diff --git a/src/app/pages/chat/chat.page.html b/src/app/pages/chat/chat.page.html index ba5d7fbca..c73acf6c0 100644 --- a/src/app/pages/chat/chat.page.html +++ b/src/app/pages/chat/chat.page.html @@ -46,64 +46,64 @@
- -
-
- - - -
-
-
-
- - -
-
- {{t.name}} -
+ +
+
+ + + +
+
+
+
+ + +
+
+ {{room.value.name}}
- - +
+
+
+
+
{{room.value.duration}}
+
+
+ {{room.value.lastMessage.msg}} + + + + {{room.value.lastMessage.file.name || room.value.lastMessage.file.subject }} + + +
+ + Fotografia
-
{{showDateDuration(dm._updatedAt)}}
-
-
- {{dm.lastMessage.msg}} - - - - {{dm.lastMessage.file.name || dm.lastMessage.file.subject }} - - -
- - Fotografia -
-
-
+
-
- -
-
-
-
-
-
-
-
- - -
+
+ + +
+
+
+
+
+
+
+
+ +
- +
+
@@ -262,5 +262,3 @@
- - diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index 483523ea8..cc0c2e704 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -12,6 +12,7 @@ import { import { ModalController, Platform } from '@ionic/angular'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; +import { ChatService as ChatServiceGPR} from 'src/app/services/chat/chat.service' import { GroupMessagesPage } from './group-messages/group-messages.page'; import { ContactsPage } from './messages/contacts/contacts.page'; import { MessagesPage } from './messages/messages.page'; @@ -126,9 +127,11 @@ export class ChatPage implements OnInit { private sqlservice: SqliteService, private platform: Platform, private storageservice: StorageService, + public ChatServiceGPR: ChatServiceGPR, private wsService: WebsocketService, ) { + this.loggedUserChat = authService.ValidatedUserChat['data']; this.headers = new HttpHeaders(); window.onresize = (event) => { @@ -136,6 +139,7 @@ export class ChatPage implements OnInit { this.modalController.dismiss(); } }; + this.showLoader = true; console.log("CHAT PAGE"); @@ -143,6 +147,8 @@ export class ChatPage implements OnInit { wsService.messages.subscribe(msg => { console.log("Response from Websocket server: "+msg); }); + + this.load() } ngOnInit() { @@ -583,7 +589,7 @@ export class ChatPage implements OnInit { //Check if modal is opened if (this.segment == "Contactos" && this.showMessages != true) { await new Promise(resolve => setTimeout(resolve, 1000)); - await this.getDirectMessages(); + //await this.getDirectMessages(); //console.log('Timer contactos list running') } else { @@ -592,7 +598,7 @@ export class ChatPage implements OnInit { } } else { - await this.getDirectMessages(); + //await this.getDirectMessages(); } }); } @@ -747,12 +753,12 @@ export class ChatPage implements OnInit { //Check if modal is opened if (this.segment == "Grupos" && this.showGroupMessages != true) { await new Promise(resolve => setTimeout(resolve, 1000)); - await this.getGroups(); + //await this.getGroups(); } } } else { - await this.getGroups(); + //await this.getGroups(); } }); } diff --git a/src/app/pages/chat/messages/messages.page.html b/src/app/pages/chat/messages/messages.page.html index 02df0983c..836d6ff58 100644 --- a/src/app/pages/chat/messages/messages.page.html +++ b/src/app/pages/chat/messages/messages.page.html @@ -49,7 +49,7 @@ -->
-
diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 0e72b5634..aee83350b 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -28,6 +28,7 @@ import { SqliteService } from 'src/app/services/sqlite.service'; import { elementAt } from 'rxjs-compat/operator/elementAt'; import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; +import { ChatService as ChatServiceGPR} from 'src/app/services/chat/chat.service' const IMAGE_DIR = 'stored-images'; @@ -94,7 +95,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { public ThemeService: ThemeService, private changeDetectorRef: ChangeDetectorRef, private platform: Platform, - private sqlservice: SqliteService + private sqlservice: SqliteService, + public ChatServiceGPR: ChatServiceGPR ) { this.loggedUser = authService.ValidatedUserChat['data']; this.roomId = this.navParams.get('roomId'); @@ -105,10 +107,13 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { this.modalController.dismiss(); } }; + + this.ChatServiceGPR.getRoom(this.roomId).loadHistory() + } ngOnInit() { - this.load(); + //this.load(); this.setStatus('online'); //this.loadFiles(); diff --git a/src/app/services/chat/chat.service.ts b/src/app/services/chat/chat.service.ts index 1686dd66a..501c26195 100644 --- a/src/app/services/chat/chat.service.ts +++ b/src/app/services/chat/chat.service.ts @@ -2,32 +2,111 @@ import { Injectable } from '@angular/core'; import { RoomService } from './room.service'; import { RocketChatClientService } from 'src/app/services/socket/rocket-chat-client.service'; import { MessageService } from 'src/app/services/chat/message.service' +import { SessionStore } from 'src/app/store/session.service'; @Injectable({ providedIn: 'root' }) export class ChatService { - rooms: RoomService[] = [] - group = [] + + individual: {[key: string]: RoomService} = {} + group: {[key: string]: RoomService} = {} + + loadingWholeList = false + + individualCount = 0; + groupCount = 0; constructor( private RocketChatClientService: RocketChatClientService ) { - this.getAllRoomAndSubscribe() + + (async()=>{ + await this.getAllRoom(); + this.subscribeToRoom() + })() + } - getAllRoomAndSubscribe() { - this.RocketChatClientService.getRooms().then((rooms: any) => { - rooms.result.update.forEach((roomData:any) => { - const room = new RoomService(new RocketChatClientService(), new MessageService()) - room.setData({id: roomData.lastMessage.rid}) - }); + async getAllRoom () { + this.loadingWholeList = true + + const rooms: any = await this.RocketChatClientService.getRooms(); + + rooms.result.update.forEach((roomData:any) => { + let room:RoomService; + + room = new RoomService(this.RocketChatClientService, new MessageService()) + room.setData({ + id: this.getRoomId(roomData), + name: this.getChatName(roomData), + lastMessage: this.getRoomLastMessage(roomData), + _updatedAt: roomData._updatedAt['$date'] + }) + + room.receiveMessage() + + let roomId = roomData.lastMessage.rid + + if(this.isIndividual(roomData)) { + this.individual[roomId] = room + this.individualCount++ + } else { + this.group[roomId] = room + this.groupCount++ + } + }); + + this.loadingWholeList = false } - onJoinRoom() { - // live + subscribeToRoom() { + for (const id in this.individual) { + this.RocketChatClientService.subscribe(id).then((subscription)=>{ + console.log('subscription', subscription) + }) + } + + for (const id in this.group) { + this.RocketChatClientService.subscribe(id).then((subscription)=>{ + console.log('subscription', subscription) + }) + } + } + + getRoom(id): RoomService { + try { + return this.individual[id] + } catch(e) { + return this.group[id] + } + } + + getChatName(roomData) { + if(this.isIndividual(roomData)) { + const names: String[] = roomData.usernames + const roomName = names.filter((name)=>{ + return name != SessionStore.user.RochetChatUser + })[0] + + return roomName + } else { + return roomData.fName + } + } + + getRoomId(roomData) { + return roomData.lastMessage.rid + } + + getRoomLastMessage(roomData) { + return roomData.lastMessage + } + + private isIndividual(roomData) { + return !roomData.fname } } diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index b22bacf6c..47c0c09cc 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -5,5 +5,30 @@ import { Injectable } from '@angular/core'; }) export class MessageService { + channels = [] + mentions = [] + msg = '' + rid = '' + ts = {} + u = {} + _id ='' + _updatedAt = {} + constructor() { } + + setData({channels, mentions, msg ,rid ,ts, u, _id, _updatedAt}) { + this.channels = channels + this.mentions = mentions + this.msg = msg + this.rid = rid + this.ts = ts + this.u = u + this._id = _id + this._updatedAt = _updatedAt + } + + delete() {} + + showDateDuration() {} + } diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index c921a754c..ef85e84a0 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -2,27 +2,96 @@ import { Injectable } from '@angular/core' import { RocketChatClientService } from 'src/app/services/socket/rocket-chat-client.service'; import { MessageService } from 'src/app/services/chat/message.service' import { ChatUserService } from 'src/app/services/chat/chat-user.service' +import { TimeService } from 'src/app/services/functions/time.service'; +import { ChatService } from '../chat.service'; +import { showDateDuration } from 'src/plugin/showDateDuration' @Injectable({ providedIn: 'root' }) export class RoomService { massages: MessageService[] = [] + lastMessage: MessageService; + chatUser: ChatUserService[] = [] - id = [] + id = '' + name = '' + _updatedAt = {} + private hasLoadHistory = false + duration = '' + constructor( - private RocketChatClientService: RocketChatClientService, - private MessageService: MessageService + public RocketChatClientService: RocketChatClientService, + private MessageService: MessageService, ) {} - setData({id}){ - this.id= id + setData({id, name, lastMessage, _updatedAt}) { + + this.id = id + this.name = name + this.lastMessage = lastMessage + this._updatedAt = _updatedAt + + this.calDateDuration() + } + + receiveMessage() { + this.RocketChatClientService.receiveLiveMessageFromRoom( + this.id, + this.constructor.name+this.id, + (Chatmessage) => { + + Chatmessage = this.fix_updatedAt(Chatmessage) + const message = new MessageService() + message.setData(Chatmessage.result) + this.massages.push(message) + this.calDateDuration(Chatmessage.result._updatedAt) + } + ) + } + + send(msg) { + this.RocketChatClientService.send(this.id, msg) + } + + // runs onces only + loadHistory(limit= 100) { + + if(this.hasLoadHistory){ return false } + + this.RocketChatClientService.loadHistory(this.id, limit).then((message:any) => { + console.log('loadHistory', message) + + 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) + }); + + }) + + this.hasLoadHistory = true } create() {} - sendMessage() {} - deleteMessage() {} + deleteMessage(msgId) {} 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 + } + } diff --git a/src/app/services/socket/rocket-chat-client.service.ts b/src/app/services/socket/rocket-chat-client.service.ts index 6188656f3..3f0fc0b01 100644 --- a/src/app/services/socket/rocket-chat-client.service.ts +++ b/src/app/services/socket/rocket-chat-client.service.ts @@ -207,7 +207,7 @@ import { deepFind } from 'src/plugin/deep' * @param key * @param funx */ - receiveLiveMessageFromRoom(roomId, key, funx: Function) { + receiveLiveMessageFromRoom(roomId =')(', key, funx: Function) { this.ws.registerCallback({ type:'Onmessage', @@ -300,7 +300,6 @@ import { deepFind } from 'src/plugin/deep' }, connect:(url)=> { - this.ws.connected = false this.wsUrl = url this.socket = new WebSocket(this.wsUrl); // bind function @@ -331,7 +330,7 @@ import { deepFind } from 'src/plugin/deep' send: (message: object, requestId = uuidv4(), loginRequired) => { if (this.ws.connected == false || loginRequired == true && this.isLogin == false) { // save data to send when back online - console.log('save msgQueue') + 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}) } else { let messageStr = JSON.stringify(message) diff --git a/src/app/shared/chat/messages/messages.page.html b/src/app/shared/chat/messages/messages.page.html index d35dfa92b..786a9c902 100644 --- a/src/app/shared/chat/messages/messages.page.html +++ b/src/app/shared/chat/messages/messages.page.html @@ -37,7 +37,7 @@
-
+
diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 59184d9b2..d676710f5 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -19,6 +19,7 @@ import { ThemeService } from 'src/app/services/theme.service' import { PreviewCameraPage } from 'src/app/modals/preview-camera/preview-camera.page'; import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; +import { ChatService as ChatServiceGPR} from 'src/app/services/chat/chat.service' @Component({ selector: 'app-messages', @@ -77,27 +78,17 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy public ThemeService: ThemeService, private changeDetectorRef: ChangeDetectorRef, private router: Router, + public ChatServiceGPR: ChatServiceGPR ) { + this.loggedUser = authService.ValidatedUserChat['data']; - - /* this.dm = this.navParams.get('dm'); */ } ngOnChanges(changes: SimpleChanges): void { - this.load(); - - //throw new Error('Method not implemented.'); + this.ChatServiceGPR.getRoom(this.roomId).loadHistory() } ngOnInit() { - this.scrollToBottom(); - - /* setInterval(()=>{ */ - this.load(); - /* }, 9000); */ - console.log(this.roomId); - console.log("Chat route", this.route.url) - this.setStatus('online'); } @@ -223,19 +214,11 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } sendMessage() { - let body = { - "message": - { - "rid": this.roomId, "msg": this.message, - } - } - this.chatService.sendMessage(body).subscribe(res=> { - this.scrollingOnce = true; - }); + this.ChatServiceGPR.getRoom(this.roomId).send(this.message) this.message = ""; } - deleteMessage(msgId:string){ + deleteMessage(msgId:string) { let body = { "roomId": this.roomId, "msgId": msgId, @@ -247,23 +230,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy }); */ } - 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.serverLongPull(res) - /* this.chatService.subscribe(this.roomId).then(res => { - console.log("Real fake msg", res) - }); */ - //this.showLoader = false; - }) - } - async viewDocument(msg:any, url?:string){ if(msg.file.type == "application/img"){ let response:any = await this.fileService.getFile(msg.file.guid).toPromise(); @@ -539,7 +505,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy this.showLoader = false; //this.addDocGestaoDocumental(); } - this.loadMessages(); }); } @@ -555,7 +520,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy if (res['success'] == true) { // Show Error //showMessage(response.statusText); - this.loadMessages() this.messages = res['messages'].reverse(); this.chatMessageStore.add(roomId, this.messages) @@ -567,7 +531,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy else{ if(document.querySelector('app-messages')){ await new Promise(resolve => setTimeout(resolve, 5000)); - await this.serverLongPull(); + // await this.serverLongPull(); this.getDirectMessages.emit(); console.log('Timer message running') } @@ -580,10 +544,11 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } */ }, (error)=>{ console.log(error); - this.serverLongPull(); + // this.serverLongPull(); }); - }sliderOpts = { + } + sliderOpts = { zoom: false, slidesPerView: 1.5, spaceBetween: 20, diff --git a/src/plugin/showDateDuration.js b/src/plugin/showDateDuration.js new file mode 100644 index 000000000..4e8301a3b --- /dev/null +++ b/src/plugin/showDateDuration.js @@ -0,0 +1,42 @@ + +function addZero(i) { + if (i < 10) { + i = "0" + i; + } + return i; +} + +function showDateDuration(start) { + let end; + end = new Date(); + start = new Date(start); + let customizedDate; + + + const totalSeconds = Math.floor((end - (start))/1000);; + const totalMinutes = Math.floor(totalSeconds/60); + const totalHours = Math.floor(totalMinutes/60); + const totalDays = Math.floor(totalHours/24); + + const hours = totalHours - ( totalDays * 24 ); + const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 ); + const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 ); + + if(totalDays == 0){ + if(start.getDate() == new Date().getDate()){ + let time = start.getHours() + ":" + addZero(start.getUTCMinutes()); + return time; + } + else{ + return 'Ontem'; + } + } + else{ + let date = addZero(start.getDate()) + "/" + addZero(start.getMonth()+1) + "/" + start.getFullYear(); + return date; + } +} + +module.exports = { + showDateDuration: showDateDuration +}; \ No newline at end of file