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
+17
View File
@@ -19818,6 +19818,23 @@
"glob": "^7.1.3" "glob": "^7.1.3"
} }
}, },
"rocket.chat.realtime.api.rxjs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/rocket.chat.realtime.api.rxjs/-/rocket.chat.realtime.api.rxjs-2.1.1.tgz",
"integrity": "sha512-R+aAbUi66CBwsXuji0AsQGOrUx4STXw9I8lf4hpPK/mRocyjcA+r+ri0bDHGoB0FGnooSvkvauqpy+RjbB2dEg==",
"requires": {
"crypto-js": "^3.1.9-1",
"rxjs": "^6.4.0",
"uuid": "^3.1.0"
},
"dependencies": {
"crypto-js": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-3.3.0.tgz",
"integrity": "sha512-DIT51nX0dCfKltpRiXV+/TVZq+Qq2NgF4644+K7Ttnla7zEzqc+kjJyiB96BHNyUTBxyjzRcZYpUdZa+QAqi6Q=="
}
}
},
"rsvp": { "rsvp": {
"version": "4.8.5", "version": "4.8.5",
"resolved": "https://registry.npmjs.org/rsvp/-/rsvp-4.8.5.tgz", "resolved": "https://registry.npmjs.org/rsvp/-/rsvp-4.8.5.tgz",
+1
View File
@@ -136,6 +136,7 @@
"pdfjs": "^2.4.6", "pdfjs": "^2.4.6",
"pdfjs-dist": "^2.9.359", "pdfjs-dist": "^2.9.359",
"puppeteer": "^10.1.0", "puppeteer": "^10.1.0",
"rocket.chat.realtime.api.rxjs": "^2.1.1",
"rxjs": "~6.6.3", "rxjs": "~6.6.3",
"rxjs-compat": "^6.6.7", "rxjs-compat": "^6.6.7",
"sharp": "^0.29.1", "sharp": "^0.29.1",
+7 -3
View File
@@ -17,7 +17,6 @@ import { File } from '@ionic-native/file/ngx';
/* import { WebNotificationPopupService } from '../services/notification/web-notification-popup.service'; */ /* import { WebNotificationPopupService } from '../services/notification/web-notification-popup.service'; */
import { DocumentCounterService } from '../services/worker/document-counter.service'; import { DocumentCounterService } from '../services/worker/document-counter.service';
import { PermissionService } from '../services/worker/permission.service'; import { PermissionService } from '../services/worker/permission.service';
import { Network } from '@ionic-native/network/ngx';
import { BackgroundService } from 'src/app/services/background.service'; import { BackgroundService } from 'src/app/services/background.service';
import { OfflineManagerService } from 'src/app/services/offline-manager.service'; import { OfflineManagerService } from 'src/app/services/offline-manager.service';
import { Storage } from '@ionic/storage'; import { Storage } from '@ionic/storage';
@@ -27,7 +26,9 @@ import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
import { SqliteService } from 'src/app/services/sqlite.service'; import { SqliteService } from 'src/app/services/sqlite.service';
import { Device } from '@capacitor/device'; import { Device } from '@capacitor/device';
import { RouteService } from 'src/app/services/route.service'; import { RouteService } from 'src/app/services/route.service';
import { WsChatService } from 'src/app/services/chat/ws-chat.service';
import { environment } from 'src/environments/environment';
import { v4 as uuidv4 } from 'uuid'
@Component({ @Component({
selector: 'app-home', selector: 'app-home',
@@ -77,6 +78,7 @@ export class HomePage implements OnInit {
status: string = ""; status: string = "";
audioName: string = ""; audioName: string = "";
constructor( constructor(
private router: Router, private router: Router,
public modalCtrl: AlertController, public modalCtrl: AlertController,
@@ -97,7 +99,8 @@ export class HomePage implements OnInit {
private processservice: ProcessesService, private processservice: ProcessesService,
private screenOrientation: ScreenOrientation, private screenOrientation: ScreenOrientation,
private sqliteservice: SqliteService, private sqliteservice: SqliteService,
private RouteService: RouteService) { private RouteService: RouteService,
private WsChatService: WsChatService) {
/* this.webNotificationPopupService.askNotificationPermission() */ /* this.webNotificationPopupService.askNotificationPermission() */
@@ -273,3 +276,4 @@ export class HomePage implements OnInit {
} }
} }
+169
View File
@@ -0,0 +1,169 @@
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;
};
}
@@ -0,0 +1,20 @@
export interface wsCallbacksParams {
type: 'Offline' | 'Online' | 'Open' | 'Onmessage',
funx: Function
runOnces?: boolean
requestId?: string
key?: string
}
export interface msgQueue {
message: object,
requestId: string,
loginRequired: boolean
}
export interface send {
message: object
requestId?: string
loginRequired?: boolean
}
+2
View File
@@ -56,6 +56,8 @@ export class UserSession {
TypeShare: number; TypeShare: number;
}[] }[]
UserName: string UserName: string
Password: string
RochetChatUser: string
Profile: any; Profile: any;
LoginPreference: 'None' | 'Password' | 'Pin' | null; LoginPreference: 'None' | 'Password' | 'Pin' | null;
PIN: string PIN: string
+73 -79
View File
@@ -4,7 +4,7 @@
<ion-content class="height-100 container-wrapper"> <ion-content class="height-100 container-wrapper">
<ion-refresher name="refresher" slot="fixed" (ionRefresh)="doRefresh($event)"> <ion-refresher name="refresher" slot="fixed" (ionRefresh)="doRefresh($event)">
<ion-progress-bar type="indeterminate" *ngIf="showLoader"></ion-progress-bar> <ion-progress-bar type="indeterminate" *ngIf="wsChatMethodsService.loadingWholeList"></ion-progress-bar>
<ion-refresher-content> <ion-refresher-content>
</ion-refresher-content> </ion-refresher-content>
</ion-refresher> </ion-refresher>
@@ -25,9 +25,6 @@
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " slot="end" src="assets/images/icons-chat-new-group.svg" ></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'default' " slot="end" src="assets/images/icons-chat-new-group.svg" ></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' " slot="end" src="assets/images/theme/gov/icons-chat-new-group.svg" ></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'gov' " slot="end" src="assets/images/theme/gov/icons-chat-new-group.svg" ></ion-icon>
</button> </button>
<button *ngIf="hideRefreshBtn" class="btn-no-color" (click)="refreshing()">
<ion-icon class="title-icon font-awesome" name="reload-circle"></ion-icon>
</button>
</div> </div>
</div> </div>
<ion-toolbar> <ion-toolbar>
@@ -43,96 +40,96 @@
<div class=" aside overflow-y-auto d-flex flex-wrap flex-grow-1"> <div class=" aside overflow-y-auto d-flex flex-wrap flex-grow-1">
<div class="width-100" [ngSwitch]="segment"> <div class="width-100" [ngSwitch]="segment">
<ion-list *ngSwitchCase="'Contactos'"> <ion-list *ngSwitchCase="'Contactos'">
<ion-item-sliding> <ion-item-sliding>
<div class="item item-hover width-100 d-flex ion-no-padding ion-no-margin" <div class="item item-hover width-100 d-flex ion-no-padding ion-no-margin"
*ngFor="let dm of userDirectMessages" *ngFor="let room of wsChatMethodsService.dm | keyvalue"
[class.item-active]="dm._id == idSelected"> [class.item-active]="room.value.id == idSelected">
<div class="item-icon"> <div class="item-icon">
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="icon" slot="start" src="assets/images/icons-chat-chat-40.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="icon" slot="start" src="assets/images/icons-chat-chat-40.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && dm._id != idSelected " class="icon" slot="start" src="assets/images/theme/gov/icons-chat-chat-40.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'gov' && room.value.id != idSelected " class="icon" slot="start" src="assets/images/theme/gov/icons-chat-chat-40.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && dm._id == idSelected " class="icon" slot="start" src="assets/images/theme/gov/icons-chat-chat-40-hover.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'gov' && room.value.id == idSelected " class="icon" slot="start" src="assets/images/theme/gov/icons-chat-chat-40-hover.svg"></ion-icon>
</div> </div>
<div [class.highlight]="dm._id =='cjFv5XfreKz5j3fWW'" <div [class.highlight]="room.value.id =='cjFv5XfreKz5j3fWW'"
(click)="openMessagesPage(dm._id)" (click)="openMessagesPage(room.value.id)"
class="item-content flex-grow-1 cursor-pointer"><!-- (click)="openMessages(dm)" --> class="item-content flex-grow-1 cursor-pointer"><!-- (click)="openMessages(dm)" -->
<div class="item-title-time"> <div class="item-title-time">
<div class="item-title" [class.item-title-active]="dm._id == idSelected"> <div class="item-title" [class.item-title-active]="room.value.id == idSelected">
<ion-label *ngFor="let user of dm.uids"> <ion-label >
<span *ngIf="user !=loggedUserChat.me.username"> <span >
<div *ngFor="let t of dmUsers"> <div >
<div *ngIf="user == t._id"> <div >
{{t.name}} {{room.value.name}}
</div>
</div> </div>
</span> </div>
</ion-label> </span>
</ion-label>
</div>
<div class="item-date" [class.item-date-active]="room.value.id == idSelected">{{room.value.duration}}</div>
</div>
<div *ngIf="room.value.lastMessage" class="item-description" [class.item-description-active]="room.value.id == idSelected">
<ion-label *ngIf="room.value.lastMessage">{{room.value.lastMessage.msg}}</ion-label>
<ion-label *ngIf="room.value.lastMessage.file">
<fa-icon *ngIf="room.value.lastMessage.file.type != 'application/meeting'" icon="file-alt" class="file-icon" [class.set-active-item-font-to-white]="room.value.id == idSelected"></fa-icon>
<fa-icon *ngIf="room.value.lastMessage.file.type == 'application/meeting'" icon="calendar-alt" class="file-icon" [class.set-active-item-font-to-white]="room.value.id == idSelected"></fa-icon>
<span> {{room.value.lastMessage.file.name || room.value.lastMessage.file.subject }}</span>
</ion-label>
<ion-label *ngIf="room.value.lastMessage.attachments">
<div *ngIf="room.value.lastMessage.attachments[0].image_url">
<fa-icon icon="image" class="file-icon" [class.set-active-item-font-to-white]="room.value.id == idSelected"></fa-icon>
<span> Fotografia</span>
</div> </div>
<div class="item-date" [class.item-date-active]="dm._id == idSelected">{{showDateDuration(dm._updatedAt)}}</div> </ion-label>
</div>
<div *ngIf="dm.lastMessage" class="item-description" [class.item-description-active]="dm._id == idSelected">
<ion-label *ngIf="dm.lastMessage">{{dm.lastMessage.msg}}</ion-label>
<ion-label *ngIf="dm.lastMessage.file">
<fa-icon *ngIf="dm.lastMessage.file.type != 'application/meeting'" icon="file-alt" class="file-icon" [class.set-active-item-font-to-white]="dm._id == idSelected"></fa-icon>
<fa-icon *ngIf="dm.lastMessage.file.type == 'application/meeting'" icon="calendar-alt" class="file-icon" [class.set-active-item-font-to-white]="dm._id == idSelected"></fa-icon>
<span> {{dm.lastMessage.file.name || dm.lastMessage.file.subject }}</span>
</ion-label>
<ion-label *ngIf="dm.lastMessage.attachments">
<div *ngIf="dm.lastMessage.attachments[0].image_url">
<fa-icon icon="image" class="file-icon" [class.set-active-item-font-to-white]="dm._id == idSelected"></fa-icon>
<span> Fotografia</span>
</div>
</ion-label>
</div>
</div> </div>
</div> </div>
</ion-item-sliding> </div>
<ion-item-sliding *ngIf="showLoader || userDirectMessages.length < 1"> </ion-item-sliding>
<div *ngFor="let n of numSequence(8); let i = index;" class="item item-hover width-100 d-flex ion-no-padding ion-no-margin"> <ion-item-sliding *ngIf=" wsChatMethodsService.dmCount < 1">
<div class="item-icon"><ion-icon class="icon" slot="start" src="assets/icon/icons-chat-grey.svg"></ion-icon></div> <div *ngFor="let n of numSequence(8); let i = index;" class="item item-hover width-100 d-flex ion-no-padding ion-no-margin">
<div class="item-content flex-grow-1 cursor-pointer"> <div class="item-icon"><ion-icon class="icon" slot="start" src="assets/icon/icons-chat-grey.svg"></ion-icon></div>
<div class="item-title-time"> <div class="item-content flex-grow-1 cursor-pointer">
<div class="item-title"><ion-skeleton-text animated style="width: 50%"></ion-skeleton-text></div> <div class="item-title-time">
<div class="item-date"><ion-skeleton-text animated></ion-skeleton-text></div> <div class="item-title"><ion-skeleton-text animated style="width: 50%"></ion-skeleton-text></div>
</div> <div class="item-date"><ion-skeleton-text animated></ion-skeleton-text></div>
<div class="item-description d-flex align-items-center"> </div>
<fa-icon icon="file-alt" class="file-icon"></fa-icon> <div class="item-description d-flex align-items-center">
<ion-skeleton-text animated style="width: 95%; margin-left:5%"></ion-skeleton-text> <fa-icon icon="file-alt" class="file-icon"></fa-icon>
</div> <ion-skeleton-text animated style="width: 95%; margin-left:5%"></ion-skeleton-text>
</div> </div>
</div> </div>
</ion-item-sliding> </div>
</ion-item-sliding>
</ion-list> </ion-list>
<ion-list *ngSwitchCase="'Grupos'"> <ion-list *ngSwitchCase="'Grupos'">
<ion-item-sliding *ngIf="!showLoader"> <ion-item-sliding *ngIf="!wsChatMethodsService.loadingWholeList">
<div *ngFor="let group of allGroups" <div *ngFor="let group of wsChatMethodsService.group | keyvalue"
[class.item-active]="group._id ==idSelected" [class.item-active]="group.value.id ==idSelected"
class="item item-hover d-flex"> class="item item-hover d-flex">
<div class="item-icon"> <div class="item-icon">
<!-- <ion-icon class="icon" slot="start" src="assets/images/icons-chat-group-chat-40.svg"></ion-icon> --> <!-- <ion-icon class="icon" slot="start" src="assets/images/icons-chat-group-chat-40.svg"></ion-icon> -->
<ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="icon" slot="start" src="assets/images/icons-chat-group-chat-40.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'default' " class="icon" slot="start" src="assets/images/icons-chat-group-chat-40.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && group._id != idSelected " class="icon" slot="start" src="assets/images/theme/gov/icons-chat-group-chat-40.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'gov' && group.value.id != idSelected " class="icon" slot="start" src="assets/images/theme/gov/icons-chat-group-chat-40.svg"></ion-icon>
<ion-icon *ngIf="ThemeService.currentTheme == 'gov' && group._id == idSelected " class="icon" slot="start" src="assets/images/theme/gov/icons-chat-group-chat-40-hover.svg"></ion-icon> <ion-icon *ngIf="ThemeService.currentTheme == 'gov' && group.value.id == idSelected " class="icon" slot="start" src="assets/images/theme/gov/icons-chat-group-chat-40-hover.svg"></ion-icon>
</div> </div>
<div <div
(click)="openGroupMessagesPage(group._id)" class="item-content flex-grow-1 cursor-pointer"> (click)="openGroupMessagesPage(group.value.id)" class="item-content flex-grow-1 cursor-pointer">
<div class="item-title-time"> <div class="item-title-time">
<div class="item-title" [class.item-title-active]="group._id ==idSelected"> <div class="item-title" [class.item-title-active]="group.value.id ==idSelected">
<ion-label>{{group.name.split('-').join(' ')}}</ion-label> <ion-label>{{group.value.name.split('-').join(' ')}}</ion-label>
</div> </div>
<div class="item-date" [class.item-date-active]="group._id ==idSelected" *ngIf="group.lastMessage && !group.customFields.countDownDate">{{showDateDuration(group._updatedAt)}}</div> <div class="item-date" [class.item-date-active]="group.value.id ==idSelected" *ngIf="group.value.lastMessage && !group.value.customFields.countDownDate">{{group.value.duration}}</div>
<div class="item-date" [class.item-date-active]="group._id ==idSelected" *ngIf="group.customFields.countDownDate">{{countDownDate(group.customFields.countDownDate, group._id)}}</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>
<div *ngIf="group.lastMessage" class="item-description d-flex align-items-center" [class.item-description-active]="group._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.lastMessage.u.name ?? ""}}: {{group.lastMessage.msg}} </div> <div class="item-message">{{group.value.lastMessage.u.name}}: {{group.value.lastMessage.msg}} </div>
<div class="item-files add-ellipsis" *ngIf="group.lastMessage.file"> <div class="item-files add-ellipsis" *ngIf="group.value.file">
<fa-icon *ngIf="group.lastMessage.file.type != 'application/meeting'" icon="file-alt" class="file-icon" [class.set-active-item-font-to-white]="group._id == idSelected"></fa-icon> <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>
<fa-icon *ngIf="group.lastMessage.file.type == 'application/meeting'" icon="calendar-alt" class="file-icon" [class.set-active-item-font-to-white]="group._id == idSelected"></fa-icon> <fa-icon *ngIf="group.value.lastMessage.file.type == 'application/meeting'" icon="calendar-alt" class="file-icon" [class.set-active-item-font-to-white]="group.value.id == idSelected"></fa-icon>
<span class="item-files-title"> {{group.lastMessage.file.name || group.lastMessage.file.subject}}</span> <span class="item-files-title"> {{group.value.lastMessage.file.name || group.value.file.subject}}</span>
</div> </div>
<div class="item-files" *ngIf="group.lastMessage.attachments"> <div class="item-files" *ngIf="group.value.attachments">
<div *ngIf="group.lastMessage.attachments[0].image_url"> <div *ngIf="group.value.value.lastMessage.attachments[0].image_url">
<fa-icon icon="image" class="file-icon" [class.set-active-item-font-to-white]="group._id == idSelected"></fa-icon> <fa-icon icon="image" class="file-icon" [class.set-active-item-font-to-white]="group.value.id == idSelected"></fa-icon>
<span> Fotografia</span> <span> Fotografia</span>
</div> </div>
</div> </div>
@@ -140,7 +137,7 @@
</div> </div>
</div> </div>
</ion-item-sliding> </ion-item-sliding>
<ion-item-sliding *ngIf="showLoader || allGroups.length < 1"> <ion-item-sliding *ngIf="wsChatMethodsService.loadingWholeList || wsChatMethodsService.groupCount < 1">
<div *ngFor="let n of numSequence(8); let i = index;" class="item item-hover width-100 d-flex ion-no-padding ion-no-margin"> <div *ngFor="let n of numSequence(8); let i = index;" class="item item-hover width-100 d-flex ion-no-padding ion-no-margin">
<div class="item-icon"><ion-icon class="icon" slot="start" src="assets/icon/icons-group-chat-grey.svg"></ion-icon></div> <div class="item-icon"><ion-icon class="icon" slot="start" src="assets/icon/icons-group-chat-grey.svg"></ion-icon></div>
<div class="item-content flex-grow-1 cursor-pointer"> <div class="item-content flex-grow-1 cursor-pointer">
@@ -178,7 +175,6 @@
(showEmptyContainer)="showEmptyContainer()" (showEmptyContainer)="showEmptyContainer()"
(showEmptyContainer)="showEmptyContainer()" (showEmptyContainer)="showEmptyContainer()"
(openNewEventPage)="openNewEventPage($event)" (openNewEventPage)="openNewEventPage($event)"
(getDirectMessages)="getDirectMessages($event)"
[style.display]="showMessages ? 'flex' : 'none'" [style.display]="showMessages ? 'flex' : 'none'"
[roomId]="roomId" [roomId]="roomId"
[showMessages]="showMessages" #messagecontainer> [showMessages]="showMessages" #messagecontainer>
@@ -259,5 +255,3 @@
</div> </div>
</div> </div>
</ion-content> </ion-content>
+33 -106
View File
@@ -12,6 +12,7 @@ import {
import { ModalController, Platform } from '@ionic/angular'; import { ModalController, Platform } from '@ionic/angular';
import { AuthService } from 'src/app/services/auth.service'; import { AuthService } from 'src/app/services/auth.service';
import { ChatService } from 'src/app/services/chat.service'; import { ChatService } from 'src/app/services/chat.service';
import { WsChatMethodsService} from 'src/app/services/chat/ws-chat-methods.service'
import { GroupMessagesPage } from './group-messages/group-messages.page'; import { GroupMessagesPage } from './group-messages/group-messages.page';
import { ContactsPage } from './messages/contacts/contacts.page'; import { ContactsPage } from './messages/contacts/contacts.page';
import { MessagesPage } from './messages/messages.page'; import { MessagesPage } from './messages/messages.page';
@@ -123,9 +124,10 @@ export class ChatPage implements OnInit {
private router: Router, private router: Router,
private sqlservice: SqliteService, private sqlservice: SqliteService,
private platform: Platform, private platform: Platform,
private storageservice: StorageService private storageservice: StorageService,
public wsChatMethodsService: WsChatMethodsService,
) { ) {
this.loggedUserChat = authService.ValidatedUserChat['data']; this.loggedUserChat = authService.ValidatedUserChat['data'];
this.headers = new HttpHeaders(); this.headers = new HttpHeaders();
window.onresize = (event) => { window.onresize = (event) => {
@@ -133,34 +135,31 @@ export class ChatPage implements OnInit {
this.modalController.dismiss(); this.modalController.dismiss();
} }
}; };
this.showLoader = true; this.showLoader = true;
//this.load()
} }
ngOnInit() { ngOnInit() {
console.log(this.loggedUserChat); console.log(this.wsChatMethodsService.group);
this.segment = "Contactos"; this.segment = "Contactos";
this.authService.userData$.subscribe((res: any) => { this.authService.userData$.subscribe((res: any) => {
this.loggedUser = res; this.loggedUser = res;
console.log(this.loggedUser); console.log(this.loggedUser);
this.load();
this.getDirectMessagesDB(); this.getDirectMessagesDB();
this.getGroupsDB() this.getGroupsDB()
}); });
/* websocket functions */
//this.sendMsg();
/* Fim websocket functions */
this.hideRefreshButton(); this.hideRefreshButton();
this.getChatMembers(); this.getChatMembers();
//Teste
let t = this.showDateDuration(new Date()); let t = this.showDateDuration(new Date());
console.log(t);
this.setStatus('away'); this.setStatus('away');
/* if(this.dataService.get("newGroup")){ /* if(this.dataService.get("newGroup")){
@@ -222,21 +221,6 @@ export class ChatPage implements OnInit {
} }
} }
/* loadMessage(){
this.chatService.messages.subscribe(msg => {
console.log("Response from websocket: " + msg);
});
} */
/* sendMsg() {
console.log("new message from client to websocket: ", this.message);
this.chatService.messages.next(this.message);
this.message.msg = "";
} */
/* Fim websockets functions */
closeAllDesktopComponents() { closeAllDesktopComponents() {
this.showMessages = false; this.showMessages = false;
this.showContacts = false; this.showContacts = false;
@@ -379,38 +363,21 @@ export class ChatPage implements OnInit {
} }
onSegmentChange() { onSegmentChange() {
this.load(); //this.load();
} }
doRefresh(event) { doRefresh(event) {
setTimeout(() => { setTimeout(() => {
this.load(); //this.load();
event.target.complete(); event.target.complete();
}, 1000); }, 1000);
} }
refreshing() {
this.load();
}
load() {
switch (this.segment) {
case "Contactos":
this.showLoader = true;
this.getDirectMessages();
break;
case "Grupos":
this.showLoader = true;
this.getGroups();
break;
}
}
customRoom() { customRoom() {
let params = new HttpParams(); let params = new HttpParams();
params = params.set("types", "c"); params = params.set("types", "c");
this.chatService.customsRooms(params).subscribe(res => { this.chatService.customsRooms(params).subscribe(res => {
console.log(res); //console.log(res);
}); });
} }
@@ -424,9 +391,9 @@ export class ChatPage implements OnInit {
var dateB = new Date(b._updatedAt).getTime(); var dateB = new Date(b._updatedAt).getTime();
return dateB - dateA; return dateB - dateA;
}); });
console.log('DIRECTMESSAGE FROM DB', this.userDirectMessages); //console.log('DIRECTMESSAGE FROM DB', this.userDirectMessages);
console.log('ROOMS FROM DB', rooms) //console.log('ROOMS FROM DB', rooms)
}) })
this.storageservice.get('chatusers').then((users) => { this.storageservice.get('chatusers').then((users) => {
@@ -434,7 +401,7 @@ export class ChatPage implements OnInit {
}) })
} else { } else {
this.sqlservice.getAllChatRoom().then((rooms: any) => { this.sqlservice.getAllChatRoom().then((rooms: any) => {
console.log('ROOMS FROM DB', rooms) //console.log('ROOMS FROM DB', rooms)
let roomsArray = []; let roomsArray = [];
rooms.forEach(element => { rooms.forEach(element => {
let roomListDB = { let roomListDB = {
@@ -454,13 +421,13 @@ export class ChatPage implements OnInit {
var dateB = new Date(b._updatedAt).getTime(); var dateB = new Date(b._updatedAt).getTime();
return dateB - dateA; return dateB - dateA;
}); });
console.log('DIRECTMESSAGE FROM DB', this.userDirectMessages); //console.log('DIRECTMESSAGE FROM DB', this.userDirectMessages);
console.log('ROOMS FROM DB', rooms) //console.log('ROOMS FROM DB', rooms)
}) })
this.sqlservice.getAllChatUsers().then((userslist: any) => { this.sqlservice.getAllChatUsers().then((userslist: any) => {
console.log('USERS FOM DB 1', userslist) //console.log('USERS FOM DB 1', userslist)
let chatusersArray = []; let chatusersArray = [];
userslist.forEach(element => { userslist.forEach(element => {
console.log('USERS FOM DB 2', element) console.log('USERS FOM DB 2', element)
@@ -491,7 +458,7 @@ export class ChatPage implements OnInit {
_updatedAt: element._updatedAt _updatedAt: element._updatedAt
} }
console.log(' Web TRANSFORM ROOM LIST', roomList) //console.log(' Web TRANSFORM ROOM LIST', roomList)
roomsArray.push(roomList) roomsArray.push(roomList)
}); });
@@ -508,7 +475,7 @@ export class ChatPage implements OnInit {
updatedat: element._updatedAt updatedat: element._updatedAt
} }
console.log('TRANSFORM ROOM LIST', roomList) //console.log('TRANSFORM ROOM LIST', roomList)
this.sqlservice.addChatListRoom(roomList); this.sqlservice.addChatListRoom(roomList);
}); });
} }
@@ -518,72 +485,31 @@ export class ChatPage implements OnInit {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
let usersArray = []; let usersArray = [];
users.forEach(element => { users.forEach(element => {
console.log('TRANSFORM USER CHAT 1', element) //console.log('TRANSFORM USER CHAT 1', element)
let chatusers = { let chatusers = {
_id: element._id, _id: element._id,
name: element.name, name: element.name,
username: element.username username: element.username
} }
console.log('TRANSFORM USER CHAT 2', chatusers) //console.log('TRANSFORM USER CHAT 2', chatusers)
usersArray.push(chatusers); usersArray.push(chatusers);
}); });
await this.storageservice.remove('chatusers'); await this.storageservice.remove('chatusers');
await this.storageservice.store('chatusers',usersArray); await this.storageservice.store('chatusers',usersArray);
} else { } else {
users.forEach(element => { users.forEach(element => {
console.log('TRANSFORM USER CHAT 1', element) //console.log('TRANSFORM USER CHAT 1', element)
let chatusers = { let chatusers = {
id: element._id, id: element._id,
name: element.name, name: element.name,
username: element.username username: element.username
} }
console.log('TRANSFORM USER CHAT 2', chatusers) //console.log('TRANSFORM USER CHAT 2', chatusers)
this.sqlservice.addChatListUsers(chatusers); this.sqlservice.addChatListUsers(chatusers);
}); });
} }
} }
async getDirectMessages(event?) {
this.chatService.getAllDirectMessages().subscribe(async (res: any) => {
this.showLoader = false;
this.transformDataRoomList(res.ims)
this.getDirectMessagesDB()
console.log('Chat list', res);
if (res != 200) {
/* if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.userDirectMessages = res.ims.sort((a, b) => {
var dateA = new Date(a._updatedAt).getTime();
var dateB = new Date(b._updatedAt).getTime();
return dateB - dateA;
});
} */
//console.log(res.ims);
//console.log(this.userDirectMessages);
if (this.route.url != "/home/chat") {
//console.log("Timer message stop")
}
else {
//console.log('TIMER');
//Check if modal is opened
if (this.segment == "Contactos" && this.showMessages != true) {
await new Promise(resolve => setTimeout(resolve, 1000));
await this.getDirectMessages();
//console.log('Timer contactos list running')
}
else {
//console.log('No timer!');
}
}
}
else {
await this.getDirectMessages();
}
});
}
showDateDuration(start: any) { showDateDuration(start: any) {
return this.timeService.showDateDuration(start); return this.timeService.showDateDuration(start);
} }
@@ -595,13 +521,13 @@ export class ChatPage implements OnInit {
async getChatMembers() { async getChatMembers() {
//return await this.chatService.getMembers(roomId).toPromise(); //return await this.chatService.getMembers(roomId).toPromise();
this.chatService.getAllUsers().subscribe(res => { this.chatService.getAllUsers().subscribe(res => {
console.log('chatusers', res); //console.log('chatusers', res);
this.transformDataUserList(res['users']) this.transformDataUserList(res['users'])
/* if (this.platform.is('desktop') || this.platform.is('mobileweb')) { /* if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.dmUsers = res['users'].filter(data => data.username != this.loggedUserChat.me.username); this.dmUsers = res['users'].filter(data => data.username != this.loggedUserChat.me.username);
console.log(this.dmUsers); //console.log(this.dmUsers);
} */ }*/
}); });
} }
@@ -626,6 +552,7 @@ export class ChatPage implements OnInit {
}); });
//console.log('GROUPS FROM DB', this.allGroups)
}) })
this.storageservice.get('chatusers').then((users) => { this.storageservice.get('chatusers').then((users) => {
@@ -654,7 +581,7 @@ export class ChatPage implements OnInit {
var dateB = new Date(b._updatedAt).getTime(); var dateB = new Date(b._updatedAt).getTime();
return dateB - dateA; return dateB - dateA;
}); });
console.log('Group FROM DB', this.allGroups); //console.log('Group FROM DB', this.allGroups);
}) })
@@ -741,18 +668,18 @@ export class ChatPage implements OnInit {
//console.log(this.allGroups); //console.log(this.allGroups);
/* }); */ /* }); */
if (this.route.url != "/home/chat") { if (this.route.url != "/home/chat") {
console.log("Timer message stop") //console.log("Timer message stop")
} }
else { else {
//Check if modal is opened //Check if modal is opened
if (this.segment == "Grupos" && this.showGroupMessages != true) { if (this.segment == "Grupos" && this.showGroupMessages != true) {
await new Promise(resolve => setTimeout(resolve, 1000)); await new Promise(resolve => setTimeout(resolve, 1000));
await this.getGroups(); //await this.getGroups();
} }
} }
} }
else { else {
await this.getGroups(); //await this.getGroups();
} }
}); });
} }
@@ -802,7 +729,7 @@ export class ChatPage implements OnInit {
async openMessagesModal(roomId: any) { async openMessagesModal(roomId: any) {
this.closeAllDesktopComponents(); this.closeAllDesktopComponents();
console.log(roomId); //console.log(roomId);
const modal = await this.modalController.create({ const modal = await this.modalController.create({
component: MessagesPage, component: MessagesPage,
@@ -11,7 +11,7 @@
</div> </div>
<div class="middle-container" *ngIf="!showMessageOptions"> <div class="middle-container" *ngIf="!showMessageOptions">
<div class="middle add-ellipsis"> <div class="middle add-ellipsis">
<ion-label class="title">{{roomName}}</ion-label> <ion-label class="title">{{wsChatMethodsService.getGroupRoom(roomId).name}}</ion-label>
</div> </div>
</div> </div>
<div class="middle-container-options" *ngIf="showMessageOptions"> <div class="middle-container-options" *ngIf="showMessageOptions">
@@ -53,11 +53,11 @@
<div (click)="handleClick()" class="messages overflow-y-auto" #scrollMe> <div (click)="handleClick()" class="messages overflow-y-auto" #scrollMe>
<div class="welcome-text"> <div class="welcome-text">
<ion-label>Esta conversa passou a grupo TIAGO</ion-label><br /> <ion-label>Esta conversa passou a grupo</ion-label><br />
<ion-label>A conversa original mantêm-se como chat individual</ion-label> <ion-label>A conversa original mantêm-se como chat individual</ion-label>
</div> </div>
<div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of messages; let last = last" [class.messages-list-item-wrapper-active]="msg._id == selectedMsgId"> <div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of wsChatMethodsService.getGroupRoom(roomId).massages; let last = last" [class.messages-list-item-wrapper-active]="msg._id == selectedMsgId">
<div *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'ru' && msg.msg !=''" (press)="handlePress(msg._id)" class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}'> <div *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'au' && msg.t != 'ru' && msg.msg !=''" (press)="handlePress(msg._id)" class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}'>
<div class="title"> <div class="title">
<ion-label>{{msg.u.name ?? ""}}</ion-label> <ion-label>{{msg.u.name ?? ""}}</ion-label>
<span class="time">{{showDateDuration(msg._updatedAt)}}</span> <span class="time">{{showDateDuration(msg._updatedAt)}}</span>
@@ -137,7 +137,6 @@
<div> <div>
<div> <div>
<div class="file"> <div class="file">
<!-- <canvas id="pdf_canvas"></canvas> -->
<div (click)="viewDocument(msg.file, file.title_link)" class="file-details add-ellipsis cursor-pointer" *ngIf="msg.file"> <div (click)="viewDocument(msg.file, file.title_link)" class="file-details add-ellipsis cursor-pointer" *ngIf="msg.file">
<span *ngIf="msg.file.type"> <span *ngIf="msg.file.type">
<fa-icon *ngIf="msg.file.type == 'application/pdf'" icon="file-pdf" class="pdf-icon"></fa-icon> <fa-icon *ngIf="msg.file.type == 'application/pdf'" icon="file-pdf" class="pdf-icon"></fa-icon>
@@ -184,6 +183,14 @@
</div> </div>
{{last ? scrollToBottom() : ''}} {{last ? scrollToBottom() : ''}}
</div> </div>
<div *ngIf="msg.t == 'au'" class="info-text-leave">
<div *ngFor="let user of allUsers">
<div *ngIf="msg.msg == user.username">
<ion-label>Adicionou {{user.name}}</ion-label><br />
</div>
</div>
{{last ? scrollToBottom() : ''}}
</div>
<div *ngIf="msg.file"> <div *ngIf="msg.file">
<div *ngIf="msg.file.type == 'application/meeting'" class="info-meeting"> <div *ngIf="msg.file.type == 'application/meeting'" class="info-meeting">
<ion-label class="info-meeting-small">{{msg.u.name ?? ""}} criou esta reunião</ion-label><br /> <ion-label class="info-meeting-small">{{msg.u.name ?? ""}} criou esta reunião</ion-label><br />
@@ -25,6 +25,7 @@ import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { HttpEventType } from '@angular/common/http'; import { HttpEventType } from '@angular/common/http';
import { SqliteService } from 'src/app/services/sqlite.service'; import { SqliteService } from 'src/app/services/sqlite.service';
import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.service';
@Component({ @Component({
selector: 'app-group-messages', selector: 'app-group-messages',
@@ -88,6 +89,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
private changeDetectorRef: ChangeDetectorRef, private changeDetectorRef: ChangeDetectorRef,
private sqlservice: SqliteService, private sqlservice: SqliteService,
private platform: Platform, private platform: Platform,
public wsChatMethodsService: WsChatMethodsService
) { ) {
this.loggedUserChat = authService.ValidatedUserChat['data']; this.loggedUserChat = authService.ValidatedUserChat['data'];
this.isGroupCreated = true; this.isGroupCreated = true;
@@ -97,6 +99,14 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.modalController.dismiss(); this.modalController.dismiss();
} }
}; };
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory();
this.wsChatMethodsService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked;
setTimeout(()=>{
this.scrollToBottomClicked()
}, 50)
} }
ngOnInit() { ngOnInit() {
@@ -208,7 +218,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
} catch(err) { } } catch(err) { }
} }
scrollToBottomClicked(): void { scrollToBottomClicked = () => {
try { try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch(err) { } } catch(err) { }
@@ -312,18 +322,8 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
sendMessage(){ sendMessage() {
let body = { this.wsChatMethodsService.getDmRoom(this.roomId).send(this.message)
"message": { "rid": this.roomId, "msg": this.message }
}
this.chatService.sendMessage(body).subscribe(res=> {
this.getRoomInfo();
this.scrollingOnce = true;
},(error) => {
});
this.message = ""; this.message = "";
} }
@@ -12,9 +12,9 @@
</button> </button>
</div> </div>
<div class="middle-container" *ngIf="!showMessageOptions"> <div class="middle-container" *ngIf="!showMessageOptions">
<div class="middle" *ngFor="let users of dmUsers"> <div class="middle">
<ion-label class="title">{{users.name}}</ion-label> <ion-label class="title">{{wsChatMethodsService.getDmRoom(roomId).name}}</ion-label>
<span><ion-icon class="{{users.status}}" name="ellipse"></ion-icon></span> <!-- <span><ion-icon class="{{users.status}}" name="ellipse"></ion-icon></span> -->
</div> </div>
</div> </div>
<div class="middle-container-options" *ngIf="showMessageOptions"> <div class="middle-container-options" *ngIf="showMessageOptions">
@@ -49,7 +49,7 @@
</ion-refresher-content> </ion-refresher-content>
</ion-refresher> --> </ion-refresher> -->
<div (click)="handleClick()" class="messages" #scrollMe> <div (click)="handleClick()" class="messages" #scrollMe>
<div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of messages; let last = last" <div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of wsChatMethodsService.getDmRoom(this.roomId).massages; let last = last"
[class.messages-list-item-wrapper-active]="msg._id == selectedMsgId" > [class.messages-list-item-wrapper-active]="msg._id == selectedMsgId" >
<div (press)="handlePress(msg._id)" class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}' (click)="downloadFileMsg(msg)"> <div (press)="handlePress(msg._id)" class='message-container incoming-{{msg.u.username!=loggedUser.me.username}}' (click)="downloadFileMsg(msg)">
<div class="title"> <div class="title">
+13 -5
View File
@@ -29,6 +29,7 @@ import { elementAt } from 'rxjs-compat/operator/elementAt';
import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page'; import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page';
import { HttpEventType } from '@angular/common/http'; import { HttpEventType } from '@angular/common/http';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.service'
const IMAGE_DIR = 'stored-images'; const IMAGE_DIR = 'stored-images';
@@ -97,7 +98,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
public ThemeService: ThemeService, public ThemeService: ThemeService,
private changeDetectorRef: ChangeDetectorRef, private changeDetectorRef: ChangeDetectorRef,
private platform: Platform, private platform: Platform,
private sqlservice: SqliteService private sqlservice: SqliteService,
public wsChatMethodsService: WsChatMethodsService
) { ) {
this.loggedUser = authService.ValidatedUserChat['data']; this.loggedUser = authService.ValidatedUserChat['data'];
this.roomId = this.navParams.get('roomId'); this.roomId = this.navParams.get('roomId');
@@ -108,10 +110,18 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.modalController.dismiss(); this.modalController.dismiss();
} }
}; };
this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory()
this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked
setTimeout(()=>{
this.scrollToBottomClicked()
}, 50)
} }
ngOnInit() { ngOnInit() {
this.load(); //this.load();
this.setStatus('online'); this.setStatus('online');
//this.loadFiles(); //this.loadFiles();
@@ -281,7 +291,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
} catch (err) { } } catch (err) { }
} }
scrollToBottomClicked(): void { scrollToBottomClicked = () => {
try { try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch (err) { } } catch (err) { }
@@ -333,8 +343,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
window.removeEventListener('scroll', this.scrollChangeCallback, true); window.removeEventListener('scroll', this.scrollChangeCallback, true);
} }
sendMessage() { sendMessage() {
let body = { let body = {
"message": "message":
+1 -1
View File
@@ -211,7 +211,7 @@ export class EventsPage implements OnInit {
let mdPessoalEvents = await this.eventService.getAllMdPessoalEvents(start, end).toPromise(); let mdPessoalEvents = await this.eventService.getAllMdPessoalEvents(start, end).toPromise();
const list = mdOficialEvents.concat(mdPessoalEvents); const list = mdOficialEvents.concat(mdPessoalEvents);
console.log("getAllMdOficialPessoalEvents", list)
this.addEventToDb(list); this.addEventToDb(list);
this.listToPresent = list this.listToPresent = list
+4 -2
View File
@@ -11,6 +11,7 @@ import { ClearStoreService } from 'src/app/services/clear-store.service';
import { ChangeProfileService } from 'src/app/services/change-profile.service'; import { ChangeProfileService } from 'src/app/services/change-profile.service';
import { ThemeService } from 'src/app/services/theme.service'; import { ThemeService } from 'src/app/services/theme.service';
import { StorageService } from 'src/app/services/storage.service'; import { StorageService } from 'src/app/services/storage.service';
import { ChatService } from 'src/app/services/chat.service';
@Component({ @Component({
selector: 'app-login', selector: 'app-login',
@@ -39,7 +40,7 @@ export class LoginPage implements OnInit {
private clearStoreService: ClearStoreService, private clearStoreService: ClearStoreService,
private changeProfileService: ChangeProfileService, private changeProfileService: ChangeProfileService,
public ThemeService: ThemeService, public ThemeService: ThemeService,
private storageservice: StorageService, private storageservice: StorageService
) {} ) {}
ngOnInit() { ngOnInit() {
@@ -97,6 +98,7 @@ export class LoginPage implements OnInit {
loader.remove() loader.remove()
// login to API successfully
if (attempt) { if (attempt) {
if (attempt.UserId == SessionStore.user.UserId) { if (attempt.UserId == SessionStore.user.UserId) {
@@ -117,7 +119,7 @@ export class LoginPage implements OnInit {
this.changeProfileService.run() this.changeProfileService.run()
await this.authService.loginChat(this.userattempt); await this.authService.loginChat(this.userattempt);
this.getToken(); this.getToken();
this.router.navigate(['/pin']); this.router.navigateByUrl('/pin', { replaceUrl: true });
} }
} }
@@ -113,8 +113,6 @@ export class NewPublicationPage implements OnInit {
// this.takePicture(); // this.takePicture();
} }
imageUrl;
async takePicture() { async takePicture() {
const capturedImage = await Camera.getPhoto({ const capturedImage = await Camera.getPhoto({
@@ -125,10 +123,8 @@ export class NewPublicationPage implements OnInit {
}); });
const response = await fetch(capturedImage.webPath!); const response = await fetch(capturedImage.webPath!);
this.imageUrl = capturedImage.webPath
const blob = await response.blob(); const blob = await response.blob();
this.convertBlobToBase64Worker.postMessage(blob); this.convertBlobToBase64Worker.postMessage(blob);
this.convertBlobToBase64Worker.onmessage = async (oEvent)=> { this.convertBlobToBase64Worker.onmessage = async (oEvent)=> {
this.capturedImage = oEvent.data this.capturedImage = oEvent.data
+1 -1
View File
@@ -22,7 +22,7 @@ export class AESEncrypt {
//Decrypting the string contained in cipherParams using the PBKDF2 key //Decrypting the string contained in cipherParams using the PBKDF2 key
var decrypted = CryptoJS.AES.encrypt(encryptData, key128Bits1000Iterations, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7 }); var decrypted = CryptoJS.AES.encrypt(encryptData, key128Bits1000Iterations, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7 });
console.log('AES encrypt',decrypted.toString()); // console.log('AES encrypt',decrypted.toString());
return decrypted.toString(); return decrypted.toString();
} }
+38 -11
View File
@@ -10,7 +10,7 @@ import { AlertController } from '@ionic/angular';
import { SessionStore } from '../store/session.service'; import { SessionStore } from '../store/session.service';
import { AESEncrypt } from '../services/aesencrypt.service'; import { AESEncrypt } from '../services/aesencrypt.service';
import { CookieService } from 'ngx-cookie-service'; import { CookieService } from 'ngx-cookie-service';
import { WsChatService } from 'src/app/services/chat/ws-chat.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
@@ -19,7 +19,9 @@ export class AuthService {
userId$ = new BehaviorSubject<any>(''); userId$ = new BehaviorSubject<any>('');
headers: HttpHeaders; headers: HttpHeaders;
public ValidatedUser: UserSession; public ValidatedUser: UserSession;
public ValidatedUserChat:any; public wsValidatedUserChat:any;
public ValidatedUserChat:any = {}
public isWsAuthenticated: boolean = false;
opts:any; opts:any;
constructor( constructor(
@@ -29,12 +31,22 @@ export class AuthService {
public alertController: AlertController, public alertController: AlertController,
private aesencrypt: AESEncrypt, private aesencrypt: AESEncrypt,
private cookieService: CookieService, private cookieService: CookieService,
) { private WsChatService: WsChatService) {
this.headers = new HttpHeaders(); this.headers = new HttpHeaders();
if (SessionStore.exist) { if (SessionStore.exist) {
this.ValidatedUser = SessionStore.user this.ValidatedUser = SessionStore.user
console.log('login', SessionStore.user.RochetChatUser, SessionStore.user.Password)
this.WsChatService.connect();
this.WsChatService.login().then((message) => {
console.log('rocket chat login successfully', message)
this.WsChatService.setStatus('busy')
}).catch((message)=>{
console.log('rocket chat login failed', message)
})
} }
if (localStorage.getItem("userChat") != null) { if (localStorage.getItem("userChat") != null) {
@@ -76,6 +88,9 @@ export class AuthService {
session.Profile = 'MDGPR' session.Profile = 'MDGPR'
} }
session.Password = user.password
session.RochetChatUser = user.username.split('@')[0]
session.BasicAuthKey = user.BasicAuthKey session.BasicAuthKey = user.BasicAuthKey
SessionStore.reset(session) SessionStore.reset(session)
@@ -91,24 +106,36 @@ export class AuthService {
} }
//Login to rocketChat server //Login to rocketChat server
async loginChat(user: UserForm): Promise<boolean> { async loginChat(user: UserForm) {
let postData = { let postData = {
"user": user.username, "user": user.username,
"password": user.password, "password": user.password,
} }
console.log(postData);
let responseChat = await this.httpService.post('login', postData).toPromise(); let responseChat = await this.httpService.post('login', postData).toPromise();
if(responseChat){
if(responseChat) {
setTimeout(()=>{
console.log('login', SessionStore.user.RochetChatUser, SessionStore.user.Password)
this.WsChatService.connect();
this.WsChatService.login().then((message) => {
console.log('rocket chat login successfully', message)
this.WsChatService.setStatus('online')
}).catch((message)=>{
console.log('rocket chat login failed', message)
})
}, 1)
console.log('Login to Rocket chat OK'); console.log('Login to Rocket chat OK');
this.ValidatedUserChat = responseChat; this.ValidatedUserChat = responseChat;
localStorage.setItem('userChat', JSON.stringify(responseChat)); localStorage.setItem('userChat', JSON.stringify(responseChat));
localStorage.setItem('Meteor.loginToken', responseChat['data'].authToken);
localStorage.setItem('Meteor.userId',responseChat['data'].userId);
this.cookieService.set('rc_token', responseChat['data'].authToken);
this.cookieService.set('rc_uid', responseChat['data'].userId);
this.storageService.store(AuthConnstants.AUTH, responseChat); this.storageService.store(AuthConnstants.AUTH, responseChat);
return true; return true;
} }
else{ else{
-7
View File
@@ -8,7 +8,6 @@ import { environment } from 'src/environments/environment';
import { Storage } from '@ionic/storage'; import { Storage } from '@ionic/storage';
import { Message } from 'src/app/models/message.model'; import { Message } from 'src/app/models/message.model';
import { Observable, Subject } from "rxjs/Rx"; import { Observable, Subject } from "rxjs/Rx";
import { WebsocketService } from './websocket.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -31,7 +30,6 @@ export class ChatService {
private authService: AuthService, private authService: AuthService,
private storage: Storage, private storage: Storage,
private storageService:StorageService, private storageService:StorageService,
//private wsService: WebsocketService,
) )
{ {
this.loggedUserChat = authService.ValidatedUserChat; this.loggedUserChat = authService.ValidatedUserChat;
@@ -42,11 +40,6 @@ export class ChatService {
headers: this.headers, headers: this.headers,
}; };
/* this.messages = <Subject<any>>this.wsService.connect(this.SERVER_URL).map((response: MessageEvent): any => {
let data = JSON.parse(response.data);
console.log(data);
return (JSON.stringify(data));
}); */
} }
getDocumentDetails(url:string){ getDocumentDetails(url:string){
@@ -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 { TestBed } from '@angular/core/testing';
import { MethodsService } from './methods.service'; import { MessageService } from './message.service';
describe('MethodsService', () => { describe('MessageService', () => {
let service: MethodsService; let service: MessageService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({}); TestBed.configureTestingModule({});
service = TestBed.inject(MethodsService); service = TestBed.inject(MessageService);
}); });
it('should be created', () => { 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) {
}
}
@@ -1,13 +1,13 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { SynchroService } from './synchro.service'; import { RoomService } from './room.service';
describe('SynchroService', () => { describe('RoomService', () => {
let service: SynchroService; let service: RoomService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({}); TestBed.configureTestingModule({});
service = TestBed.inject(SynchroService); service = TestBed.inject(RoomService);
}); });
it('should be created', () => { it('should be created', () => {
+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}`);
}
}}
-215
View File
@@ -1,215 +0,0 @@
import { Injectable } from '@angular/core';
import { SessionStore } from 'src/app/store/session.service';
import { v4 as uuidv4 } from 'uuid'
import { BackgroundService } from '../background.service';
import { environment } from 'src/environments/environment';
import { EventTrigger } from '../eventTrigger.service'
export interface wss {
url: string,
type: 'reflect' | 'emit'
header: {
id: string
bluePrint: string,
jwt: string
}
}
@Injectable({
providedIn: 'root'
})
class SynchroService {
/* [x: string]: any;
private connection!: WebSocket;
private id: string = uuidv4();
public conected = false
private url: string = ''
callback = function () { }
private _connected = false;
private eventtrigger: EventTrigger;
private BackgroundService = new BackgroundService()
callBacks: {
type: 'Offline' | 'Online' | 'Onmessage' | 'Chat' | 'Notification' | 'Notifications' | '',
object?: string
funx: Function
}[] = []
private msgQueue = []
constructor() {
// alert(SessionStore.user.FullName)
}
get connected() {
return this._connected
}
setUrl() {
let header = {
id: '1234',
bluePrint: '12312123',
jwt: uuidv4()
}
let wss: wss = {
header,
url: 'wss://sychro-offline.herokuapp.com/ws/some_url/',
type: 'reflect'
}
this.url = `${wss.url}${wss.header.id}/${wss.header.jwt}/${wss.header.bluePrint}/${this.id}/`
}
registerCallback(type: 'Offline' | 'Online' | 'Onmessage' | 'Chat' | 'Notifications' | 'Notification', funx: Function, object = '') {
this.callBacks.push({
type,
funx,
object
})
}
connect() {
this.connection = new WebSocket(this.url);
// bind function
this.connection.onopen = this.onopen;
this.connection.onmessage = this.onmessage;
this.connection.onclose = this.onclose;
this.connection.onerror = this.onerror;
}
private onopen = () => {
//if (this._connected === true) {
//this.BackgroundService.online()
console.log('Online', this._connected)
this.callBacks.forEach((e) => {
if (e.type == 'Online') {
e.funx()
}
})
//}
console.log('open ======================= welcome to socket server')
this._connected = true
// send all saved data due to internet connection
this.msgQueue.forEach((item, index, object) => {
this.$send(item);
object.splice(index, 1);
})
}
public $send(object: any) {
if (!this._connected) { // save data to send when back online
this.msgQueue.push(object)
}
let payload = {
message: JSON.stringify(object) || '{"person.adress.country":"1Angola"}',
username: SessionStore.user.FullName,
idConnection: this.id
}
let sendData = JSON.stringify(payload);
console.log(sendData)
this.connection.send(sendData);
}
private onmessage = async (event: any) => {
let data = JSON.parse(event.data)
let payload = JSON.parse(data.message)
payload.message = JSON.parse(payload.message)
const idConnection = payload.idConnection
const username = payload.username
if (idConnection != this.id) {
if (window['platform'].is('desktop') || this.platform.is('mobileweb')) { }
else return false
if (environment.production) return false
this.callBacks.forEach((e) => {
if (payload.message[0]) {
if (payload.message[0].Service && payload.message[0].Object && payload.message[0].IdObject) {
if (e.type == '' && !e.object) {
if (username == SessionStore.user.FullName) {
e.funx(payload.message, data)
}
}
if (e.type == 'Notifications') {
e.funx(payload.message, data)
}
}
} else if (payload.message.Service && payload.message.Object && payload.message.IdObject) {
if (e.type == 'Notification' && e.object == payload.message.Object || e.type == 'Notification' && e.object == 'any') {
e.funx(payload.message, data)
}
}
})
}
this.callback()
}
private onclose = (event: any) => {
console.log('Websocket close')
setTimeout(() => {
if (event.wasClean) {
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
console.log('[close] Connection died');
console.log('Reconnect')
// if (this._connected === false) {
// this.BackgroundService.offline();
console.log('Offline', this._connected)
this.callBacks.forEach((e) => {
if (e.type == 'Offline') {
e.funx()
}
})
//}
// status
this._connected = false
// reconnect
this.connect()
}
}, 100);
}
private onerror = (event: any) => {
console.log(`[error] ${event.message}`);
} */
}
/* export const synchro = new SynchroService()
synchro.setUrl()
synchro.connect()
window['synchro'] = synchro */
+38 -4
View File
@@ -10,9 +10,7 @@ export class ToastService {
constructor( constructor(
public toastController: ToastController, public toastController: ToastController,
private animationController: AnimationController, ) { }
private modalController: ModalController,
) { }
ngOnInit() {} ngOnInit() {}
@@ -91,6 +89,39 @@ export class ToastService {
} }
async _chatMessage(message?: any, sender?:string) {
let notification = document.createElement('div')
notification.className = 'notification'
notification.innerHTML = `
<div class="main-content width-100 pa-20">
<p class="message d-flex align-bottom success">
<ion-icon slot="end" class="title-icon pr-10" src="/assets/images/nofitication-success.svg"></ion-icon>
<p class="text">{{ message.message }}</p>
</p>
<p class="text">{{ message.sender }} </p>
</div>
`
document.body.append(notification)
notification.querySelector('.text').innerHTML = message || 'Processo efetuado'
setTimeout(()=>{
/* if (callback) {
callback()
} */
notification.style.right = "-100%"
setTimeout(()=>{
notification.remove()
},1000)
},6000)
}
async successMessage(message?: any, callback?) { async successMessage(message?: any, callback?) {
let notification = document.createElement('div') let notification = document.createElement('div')
@@ -219,7 +250,7 @@ export class ToastService {
</div> </div>
`; `;
console.log(document.querySelector('body').classList) // console.log(document.querySelector('body').classList)
document.body.append(loader) document.body.append(loader)
loader.addEventListener('click', ()=>{ loader.addEventListener('click', ()=>{
@@ -230,3 +261,6 @@ export class ToastService {
} }
} }
export const ToastsService = new ToastService(new ToastController())
+5 -2
View File
@@ -1,5 +1,6 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import * as Rx from "rxjs/Rx"; import * as Rx from "rxjs/Rx";
import { Observable, Subject } from "rxjs/Rx";
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -7,11 +8,13 @@ import * as Rx from "rxjs/Rx";
export class WebsocketService { export class WebsocketService {
message = ''; message = '';
messages = []; public messages: Subject<any>;
currentUser = ''; currentUser = '';
private subject: Rx.Subject<MessageEvent>; private subject: Rx.Subject<MessageEvent>;
constructor() { } constructor() {
console.log("CHAT WEBSOCKET");
}
public connect(url): Rx.Subject<MessageEvent> { public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) { if (!this.subject) {
@@ -3,7 +3,7 @@
<div class="main-header"> <div class="main-header">
<div class="header-top"> <div class="header-top">
<div class="middle"> <div class="middle">
<ion-label class="title">{{roomName}}</ion-label> <ion-label class="title">{{wsChatMethodsService.getGroupRoom(roomId).name}}</ion-label>
</div> </div>
<div class="right"> <div class="right">
<button class="btn-no-color" (click)="openGroupMessagesOptions()"> <button class="btn-no-color" (click)="openGroupMessagesOptions()">
@@ -23,10 +23,10 @@
</ion-label> </ion-label>
</div> </div>
</div> </div>
<div *ngIf="room.customFields.countDownDate" class="d-flex align-items-center yellow-orange pl-10"> <!-- <div *ngIf="room.customFields.countDownDate" class="d-flex align-items-center yellow-orange pl-10">
<i class="far fa-clock font-15" ></i> <i class="far fa-clock font-15" ></i>
<ion-label class="font-15 pl-10" color="warning">{{countDownDate()}}</ion-label> <ion-label class="font-15 pl-10" color="warning">{{countDownDate()}}</ion-label>
</div> </div> -->
</div> </div>
</ion-toolbar> </ion-toolbar>
</ion-header> </ion-header>
@@ -44,8 +44,8 @@
<ion-label>A conversa original mantêm-se como chat individual</ion-label> <ion-label>A conversa original mantêm-se como chat individual</ion-label>
</div> </div>
<div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of messages; let last = last"> <div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of wsChatMethodsService.getGroupRoom(roomId).massages; let last = last">
<div class="message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45" *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'ru' && msg.msg !=''" > <div class="message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45" *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'au' && msg.t != 'ru' && msg.msg !=''" >
<div class="message-item-options d-flex justify-content-end"> <div class="message-item-options d-flex justify-content-end">
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"></fa-icon> <fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"></fa-icon>
<mat-menu #beforeMenu="matMenu" xPosition="before"> <mat-menu #beforeMenu="matMenu" xPosition="before">
@@ -93,7 +93,7 @@
</div> </div>
<div class="message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45" *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'ru' && msg.alias =='documento'" > <div class="message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45" *ngIf="msg.t != 'r' && msg.t != 'ul' && msg.t != 'au' && msg.t != 'ru' && msg.alias =='documento'" >
<div class="message-item-options d-flex justify-content-end"> <div class="message-item-options d-flex justify-content-end">
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"></fa-icon> <fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"></fa-icon>
<mat-menu #beforeMenu="matMenu" xPosition="before"> <mat-menu #beforeMenu="matMenu" xPosition="before">
@@ -191,6 +191,14 @@
</div> </div>
{{last ? scrollToBottom() : ''}} {{last ? scrollToBottom() : ''}}
</div> </div>
<div *ngIf="msg.t == 'au'" class="info-text-leave">
<div *ngFor="let user of allUsers">
<div *ngIf="msg.msg == user.username">
<ion-label>Adicionou {{user.name}}</ion-label><br />
</div>
</div>
{{last ? scrollToBottom() : ''}}
</div>
<div *ngIf="msg.file" > <div *ngIf="msg.file" >
<div *ngIf="msg.file.type == 'application/meeting'" class="info-meeting"> <div *ngIf="msg.file.type == 'application/meeting'" class="info-meeting">
<ion-label class="info-meeting-small">{{msg.u.name}} criou esta reunião</ion-label><br /> <ion-label class="info-meeting-small">{{msg.u.name}} criou esta reunião</ion-label><br />
@@ -24,6 +24,7 @@ import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { HttpEventType } from '@angular/common/http'; import { HttpEventType } from '@angular/common/http';
import { Storage } from '@ionic/storage'; import { Storage } from '@ionic/storage';
import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.service';
/* /*
import * as pdfjsLib from 'pdfjs-dist'; import * as pdfjsLib from 'pdfjs-dist';
@@ -94,7 +95,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
private fileService: FileService, private fileService: FileService,
public ThemeService: ThemeService, public ThemeService: ThemeService,
private changeDetectorRef: ChangeDetectorRef, private changeDetectorRef: ChangeDetectorRef,
private storage: Storage private storage: Storage,
public wsChatMethodsService: WsChatMethodsService
) { ) {
this.loggedUserChat = authService.ValidatedUserChat['data']; this.loggedUserChat = authService.ValidatedUserChat['data'];
this.isGroupCreated = true; this.isGroupCreated = true;
@@ -105,12 +107,22 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
this.getRoomInfo(); this.getRoomInfo();
//this.scrollToBottom(); //this.scrollToBottom();
this.wsChatMethodsService.getGroupRoom(this.roomId).loadHistory();
console.log('MESSAGES'+this.wsChatMethodsService.getGroupRoom(this.roomId).massages);
this.wsChatMethodsService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked
setTimeout(()=>{
this.scrollToBottomClicked()
}, 50)
} }
ngOnInit() { ngOnInit() {
this.loggedUser = this.loggedUserChat; this.loggedUser = this.loggedUserChat;
//console.log(this.wsChatMethodsService.getRoom(this.roomId).massages);
this.loggedUser=this.loggedUserChat;
this.getRoomInfo(); this.getRoomInfo();
this.serverLongPull();
this.setStatus('online'); this.setStatus('online');
this.getChatMembers(); this.getChatMembers();
//this.getMessageDB(); //this.getMessageDB();
@@ -144,7 +156,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
} catch (err) { } } catch (err) { }
} }
scrollToBottomClicked(): void { scrollToBottomClicked = () => {
try { try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch (err) { } } catch (err) { }
@@ -384,27 +396,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
} }
sendMessage() { sendMessage() {
let body = { this.wsChatMethodsService.getDmRoom(this.roomId).send(this.message)
"message":
{
"rid": this.roomId,
"msg": this.message,
/* "attachments": [{
"color": "#ff0000",
"text": "Yay for gruggy!",
"title": "Attachment Example",
"title_link": "https://youtube.com",
"title_link_download": false,
"image_url": "https://upload.wikimedia.org/wikipedia/commons/e/ee/Chain_link_icon.png",
}] */
}
}
this.chatService.sendMessage(body).subscribe(res => {
/* this.loadGroupMessages(); */
//this.getRoomInfo();
this.scrollingOnce = true;
});
this.message = ""; this.message = "";
} }
@@ -841,47 +833,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
}); });
} }
async serverLongPull() {
if (this.route.url != "/home/chat" && document.querySelector('app-group-messages')) {
console.log("Timer message stop")
}
else {
this.chatService.getPrivateGroupMessages(this.roomId).subscribe(async res => {
if (res['success'] == true) {
// Show Error
//showMessage(response.statusText);
//this.loadMessages()
let msgOnly = res['messages'].filter(data => data.t != 'au');
//this.messages = msgOnly.reverse();
console.log('GROUP MSG FROM ROCKET',msgOnly.reverse());
this.transformData(msgOnly.reverse());
this.getMessageDB();
// Reconnect in one second
if (document.querySelector('app-group-messages')) {
await new Promise(resolve => setTimeout(resolve, 5000));
this.getGroups.emit();
console.log('Timer message running')
await this.serverLongPull();
}
}
else {
alert('HEY2')
// Got message
//let message = await response.text();
//this.loadMessages()
await this.serverLongPull();
}
}, (error) => {
console.log(error);
this.serverLongPull();
});
}
}
sliderOpts = { sliderOpts = {
zoom: false, zoom: false,
@@ -2,11 +2,9 @@
<ion-toolbar class="header-toolbar"> <ion-toolbar class="header-toolbar">
<div class="main-header"> <div class="main-header">
<div class="header-top"> <div class="header-top">
<div class="middle" *ngFor="let users of dmUsers"> <div class="middle">
<ion-label class="title">{{users.name}}</ion-label> <ion-label class="title">{{ wsChatMethodsService.getDmRoom(roomId).name }}</ion-label>
<span> <!-- <span><ion-icon class="{{users.status}}" name="ellipse"></ion-icon></span> -->
<ion-icon class="{{users.status}}" name="ellipse"></ion-icon>
</span>
</div> </div>
<div hidden class="right"> <div hidden class="right">
<button class="btn-no-color" (click)="_openMessagesOptions()"> <button class="btn-no-color" (click)="_openMessagesOptions()">
@@ -41,7 +39,7 @@
</ion-refresher> </ion-refresher>
<div class="messages" #scrollMe> <div class="messages" #scrollMe>
<div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of messages; let last = last"> <div class="messages-list-item-wrapper container-width-100" *ngFor="let msg of messages; let last = last">
<div class='message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45'> <div class='message-item incoming-{{msg.u.username!=loggedUser.me.username}} max-width-45' *ngIf="msg.msg !=''">
<div class="message-item-options d-flex justify-content-end"> <div class="message-item-options d-flex justify-content-end">
<fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer"> <fa-icon [matMenuTriggerFor]="beforeMenu" icon="chevron-down" class="message-options-icon cursor-pointer">
</fa-icon> </fa-icon>
+57 -86
View File
@@ -23,6 +23,8 @@ import { StorageService } from 'src/app/services/storage.service';
import { Directory, Filesystem } from '@capacitor/filesystem'; import { Directory, Filesystem } from '@capacitor/filesystem';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { Storage } from '@ionic/storage'; import { Storage } from '@ionic/storage';
import { WsChatMethodsService} from 'src/app/services/chat/ws-chat-methods.service'
import { WsChatService } from 'src/app/services/chat/ws-chat.service'
const IMAGE_DIR = 'stored-images'; const IMAGE_DIR = 'stored-images';
@Component({ @Component({
@@ -86,30 +88,31 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
private sqliteservice: SqliteService, private sqliteservice: SqliteService,
private storageservice: StorageService, private storageservice: StorageService,
private router: Router, private router: Router,
private storage: Storage private storage: Storage,
public wsChatMethodsService: WsChatMethodsService,
public WsChatService: WsChatService
) { ) {
this.loggedUser = authService.ValidatedUserChat['data']; this.loggedUser = authService.ValidatedUserChat['data'];
/* this.dm = this.navParams.get('dm'); */
} }
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
this.load(); this.wsChatMethodsService.getDmRoom(this.roomId).loadHistory()
this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked
this.getMessageDB();
setTimeout(()=>{
this.scrollToBottomClicked()
}, 50)
//throw new Error('Method not implemented.');
} }
ngOnInit() { ngOnInit() {
this.scrollToBottom(); this.scrollToBottom();
/* setInterval(()=>{ */
this.load();
/* }, 9000); */
console.log(this.roomId);
console.log("Chat route", this.route.url)
this.setStatus('online'); this.setStatus('online');
this.getMessageDB();
} }
onPressingMessage() { onPressingMessage() {
@@ -153,7 +156,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
ev.target.complete(); ev.target.complete();
} }
scrollToBottom(): void { scrollToBottom = () => {
try { try {
if (this.scrollingOnce) { if (this.scrollingOnce) {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
@@ -162,7 +165,8 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
} catch (err) { } } catch (err) { }
} }
scrollToBottomClicked(): void { scrollToBottomClicked = () => {
console.log('scroll')
try { try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
//this.scrollingOnce = false; //this.scrollingOnce = false;
@@ -234,20 +238,11 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
} }
sendMessage() { sendMessage() {
let body = { this.wsChatMethodsService.getDmRoom(this.roomId).send(this.message)
"message":
{
"rid": this.roomId, "msg": this.message,
}
}
this.chatService.sendMessage(body).subscribe(res => {
this.scrollingOnce = true;
});
this.message = ""; this.message = "";
} }
deleteMessage(msgId: string) { deleteMessage(msgId:string) {
let body = { let body = {
"roomId": this.roomId, "roomId": this.roomId,
"msgId": msgId, "msgId": msgId,
@@ -259,22 +254,23 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}); */ }); */
} }
getMessageDB() { getMessageDB() {
this.storage.get('chatmsg').then((msg) => { this.storage.get('chatmsg').then((msg) => {
console.log('FROM DB WEB', msg) console.log('FROM DB WEB', msg)
let msgArray = []; let msgArray = [];
msgArray = msg; msgArray = msg;
msgArray.filter(data => data._id != this.roomId); msgArray.filter(data => data._id != this.roomId);
this.messages = msgArray.reverse(); this.messages = msgArray;
console.log("MSG CHAT WEB", this.messages) console.log("MSG CHAT WEB", this.messages)
}) })
} }
async transformData(res) { async transformData(res) {
let mgsArray = []; let mgsArray = [];
res.map(async element => { res.forEach(async element => {
console.log('TRANSFORM DATA ELEMENT' ,element)
if (element.file) { if (element.file) {
if (element.file.guid) { if (element.file.guid) {
@@ -342,29 +338,13 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
} }
loadMessages() { async viewDocument(msg:any, url?:string){
//this.showLoader = true; if(msg.file.type == "application/img"){
const roomId = this.roomId let response:any = await this.fileService.getFile(msg.file.guid).toPromise();
this.chatService.getRoomMessages(this.roomId).subscribe(async res => { console.log(response);
console.log('ALL MSG FROM CHATROCK', res); alert(response);
await this.transformData(res['messages']);
//this.getFileFromLakeFS();
/* this.messages = res['messages'].reverse();
this.chatMessageStore.add(roomId, this.messages) */
console.log(this.messages); //this.openPreview(msg);
//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) {
console.log('FILE TYPE', msg.file.type)
if (msg.file.type == "application/img") {
this.downloadFileMsg(msg)
} }
else if (msg.file.type == "application/webtrix") { else if (msg.file.type == "application/webtrix") {
@@ -633,7 +613,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
this.showLoader = false; this.showLoader = false;
//this.addDocGestaoDocumental(); //this.addDocGestaoDocumental();
} }
this.loadMessages();
}); });
} }
@@ -646,43 +625,35 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
console.log('serverLongPull', res['success']); console.log('serverLongPull', res['success']);
if (res['success'] == true) { if (res['success'] == true) {
// Show Error // Show Error
//showMessage(response.statusText); //showMessage(response.statusText);
console.log('ALL MSG FROM CHATROCK', res); /* this.messages = res['messages'].reverse();
/* this.transformData(res['messages']);*/ this.chatMessageStore.add(roomId, this.messages) */
await this.transformData(res['messages']); console.log('MSG FROM ROCKET ', res['messages'].reverse())
this.getMessageDB(); /* this.transformData(res['messages'].reverse());
this.getMessageDB(); */
/* //console.log(this.messages);
this.messages = res['messages'].reverse(); // Reconnect in one second
this.chatMessageStore.add(roomId, this.messages) */ if(this.route.url != "/home/chat"){
console.log("Timer message stop")
//console.log(this.messages); }
// Reconnect in one second else{
if (this.route.url != "/home/chat") { if(document.querySelector('app-messages')){
console.log("Timer message stop") await new Promise(resolve => setTimeout(resolve, 5000));
// await this.serverLongPull();
this.getDirectMessages.emit();
console.log('Timer message running')
} }
else { }
if (document.querySelector('app-messages')) { }
await new Promise(resolve => setTimeout(resolve, 5000)); }, (error) => {
await this.serverLongPull(); console.log(error);
this.getDirectMessages.emit(); });
console.log('Timer message running')
}
}
} /* else {
// Got message
//let message = await response.text();
//this.loadMessages()
await this.serverLongPull();
} */
}, (error) => {
console.log(error);
this.serverLongPull();
}); }
} sliderOpts = { sliderOpts = {
zoom: false, zoom: false,
slidesPerView: 1.5, slidesPerView: 1.5,
spaceBetween: 20, spaceBetween: 20,
+1
View File
@@ -2,6 +2,7 @@ export const environment = {
production: true, production: true,
apiURL: 'https://gabinetedigital.dyndns.info/GabineteDigital.Services/V5/api/', apiURL: 'https://gabinetedigital.dyndns.info/GabineteDigital.Services/V5/api/',
apiChatUrl: 'https://gabinetedigitalchat.dyndns.info/api/v1/', apiChatUrl: 'https://gabinetedigitalchat.dyndns.info/api/v1/',
apiWsChatUrl: 'wss://gabinetedigitalchat.dyndns.info/websocket',
domain: 'gabinetedigital.local', domain: 'gabinetedigital.local',
defaultuser: '',//paulo.pinto paulo.pinto@gabinetedigital.local defaultuser: '',//paulo.pinto paulo.pinto@gabinetedigital.local
defaultuserpwd: '', //tabteste@006, defaultuserpwd: '', //tabteste@006,
+1
View File
@@ -7,6 +7,7 @@ export const environment = {
apiURL: 'https://gabinetedigital.dyndns.info/GabineteDigital.Services/V5/api/', apiURL: 'https://gabinetedigital.dyndns.info/GabineteDigital.Services/V5/api/',
//apiURL: 'http://gpr-dev-01.gabinetedigital.local/GabineteDigital.Services/V5/api/', //apiURL: 'http://gpr-dev-01.gabinetedigital.local/GabineteDigital.Services/V5/api/',
apiChatUrl: 'https://gabinetedigitalchat.dyndns.info/api/v1/', apiChatUrl: 'https://gabinetedigitalchat.dyndns.info/api/v1/',
apiWsChatUrl: 'wss://gabinetedigitalchat.dyndns.info/websocket',
//apiChatUrl: 'https://www.tabularium.pt/api/v1/', //apiChatUrl: 'https://www.tabularium.pt/api/v1/',
/* apiChatUrl: 'http://chat.gabinetedigital.local:3000/api/v1/', */ /* apiChatUrl: 'http://chat.gabinetedigital.local:3000/api/v1/', */
domain: 'gabinetedigital.local', //gabinetedigital.local domain: 'gabinetedigital.local', //gabinetedigital.local
+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/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script type="module" src="./assets/js/index.js"></script> <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> </head>
<body class='gov'> <body class='gov'>
+18
View File
@@ -0,0 +1,18 @@
function deepFind(obj, path) {
var paths = path.split('.')
, current = obj
, i;
for (i = 0; i < paths.length; ++i) {
if (current[paths[i]] == undefined) {
return undefined;
} else {
current = current[paths[i]];
}
}
return current;
}
module.exports = {
deepFind: deepFind,
};
+42
View File
@@ -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
};
+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
}
+68 -68
View File
@@ -19,91 +19,91 @@ describe('Puppeteer tests', () => {
// await page.goto(process.env.PUPPETEER_HOST) // await page.goto(process.env.PUPPETEER_HOST)
}) })
test('Login', async()=> { // test('Login', async()=> {
await loginTest(page) // await loginTest(page)
},30000) // },30000)
test('[table] Open create event component', async () => { // test('[table] Open create event component', async () => {
await page.setViewport({width: 1200, height: 720}); // await page.setViewport({width: 1200, height: 720});
await page.goto(process.env.PUPPETEER_HOST); // wait until page load // await page.goto(process.env.PUPPETEER_HOST); // wait until page load
await page.waitForSelector('ion-app') // await page.waitForSelector('ion-app')
// wait for footer button // // wait for footer button
await page.click('ion-tab-bar ion-tab-button:nth-child(2)') // await page.click('ion-tab-bar ion-tab-button:nth-child(2)')
await page.waitForSelector('app-agenda') // await page.waitForSelector('app-agenda')
// click add event // // click add event
await page.click('ion-content ion-row .cy-add-event') // await page.click('ion-content ion-row .cy-add-event')
// wait for component // // wait for component
await page.waitForSelector('app-new-event') // await page.waitForSelector('app-new-event')
expect(3 + 2).toBe(5); // expect(3 + 2).toBe(5);
},30000); // },30000);
test('[table] Create Event', async () => { // test('[table] Create Event', async () => {
await page.setViewport({width: 1200, height: 720}); // await page.setViewport({width: 1200, height: 720});
await page.goto(process.env.PUPPETEER_HOST); // wait until page load // await page.goto(process.env.PUPPETEER_HOST); // wait until page load
await page.waitForSelector('ion-app') // await page.waitForSelector('ion-app')
// wait for footer button // // wait for footer button
await page.click('ion-tab-bar ion-tab-button:nth-child(2)') // await page.click('ion-tab-bar ion-tab-button:nth-child(2)')
await page.waitForSelector('app-agenda') // await page.waitForSelector('app-agenda')
// click add event // // click add event
await page.click('ion-content ion-row .cy-add-event') // await page.click('ion-content ion-row .cy-add-event')
// wait for component // // wait for component
await page.waitForSelector('app-new-event') // await page.waitForSelector('app-new-event')
// subject // // subject
await page.type('app-new-event .ion-item-container input', faker.commerce.productDescription() ) // await page.type('app-new-event .ion-item-container input', faker.commerce.productDescription() )
// Location // // Location
await page.type('app-new-event .container-div:nth-child(2) input', faker.address.state()+" "+faker.address.city() ) // await page.type('app-new-event .container-div:nth-child(2) input', faker.address.state()+" "+faker.address.city() )
// Select Calendar // // Select Calendar
// await page.click('app-new-event .container-div:nth-child(3) .mat-form-field-flex') // // await page.click('app-new-event .container-div:nth-child(3) .mat-form-field-flex')
// await page.waitForSelector('.cdk-overlay-connected-position-bounding-box') // // await page.waitForSelector('.cdk-overlay-connected-position-bounding-box')
// await page.click('.cdk-overlay-connected-position-bounding-box mat-option') // // await page.click('.cdk-overlay-connected-position-bounding-box mat-option')
// select event type // // select event type
// await page.click('app-new-event .container-div:nth-child(4) .mat-form-field-flex') // // await page.click('app-new-event .container-div:nth-child(4) .mat-form-field-flex')
// await page.waitForSelector('.cdk-overlay-connected-position-bounding-box') // // await page.waitForSelector('.cdk-overlay-connected-position-bounding-box')
// await page.click('.cdk-overlay-connected-position-bounding-box mat-option') // // await page.click('.cdk-overlay-connected-position-bounding-box mat-option')
// select start day // // select start day
// await page.click('app-new-event .container-div:nth-child(5) button') // // await page.click('app-new-event .container-div:nth-child(5) button')
// await page.waitForSelector('.cdk-overlay-connected-position-bounding-box') // // await page.waitForSelector('.cdk-overlay-connected-position-bounding-box')
// await page.click('.mat-calendar-next-button') // // await page.click('.mat-calendar-next-button')
// let selectedFDay = Math.floor(Math.random()*(25-1+1)+1); // // let selectedFDay = Math.floor(Math.random()*(25-1+1)+1);
// let days = await page.$$(` .mat-calendar-body-cell `) // // let days = await page.$$(` .mat-calendar-body-cell `)
// await days[selectedFDay].click() // // await days[selectedFDay].click()
// await page.click('.cdk-overlay-connected-position-bounding-box .actions button') // // await page.click('.cdk-overlay-connected-position-bounding-box .actions button')
// select end day // // select end day
// await page.click('app-new-event .container-div:nth-child(6) button') // // await page.click('app-new-event .container-div:nth-child(6) button')
// await page.waitForSelector('.cdk-overlay-connected-position-bounding-box') // // await page.waitForSelector('.cdk-overlay-connected-position-bounding-box')
// await page.click('.mat-calendar-next-button') // // await page.click('.mat-calendar-next-button')
// days = await page.$$(` .mat-calendar-body-cell `) // // days = await page.$$(` .mat-calendar-body-cell `)
// await days[selectedFDay+1].click() // // await days[selectedFDay+1].click()
// await page.click('.cdk-overlay-connected-position-bounding-box .actions button') // // await page.click('.cdk-overlay-connected-position-bounding-box .actions button')
// await page.click('app-new-event .container-div:nth-child(7) .mat-form-field-flex') // // await page.click('app-new-event .container-div:nth-child(7) .mat-form-field-flex')
// await page.waitForSelector('.cdk-overlay-connected-position-bounding-box') // // await page.waitForSelector('.cdk-overlay-connected-position-bounding-box')
// await page.click('.cdk-overlay-connected-position-bounding-box mat-option') // // await page.click('.cdk-overlay-connected-position-bounding-box mat-option')
await page.click('app-new-event .container-div:nth-child(8) .add-people') // await page.click('app-new-event .container-div:nth-child(8) .add-people')
await page.waitForSelector('app-attendee-modal .ng-star-inserted:nth-child(2)') // await page.waitForSelector('app-attendee-modal .ng-star-inserted:nth-child(2)')
await page.click('app-attendee-modal .ng-star-inserted:nth-child(2)') // await page.click('app-attendee-modal .ng-star-inserted:nth-child(2)')
// save // // save
await page.click('app-attendee-modal ion-footer ion-buttons:nth-child(2)') // await page.click('app-attendee-modal ion-footer ion-buttons:nth-child(2)')
// save // // save
let buttons = await page.$$('app-new-event ion-footer ion-buttons') // let buttons = await page.$$('app-new-event ion-footer ion-buttons')
buttons[1].click() // buttons[1].click()
await page.waitForSelector('.notification .success') // await page.waitForSelector('.notification .success')
expect(3 + 2).toBe(5); // expect(3 + 2).toBe(5);
},60000); // },60000);
}); });