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
+1 -1
View File
@@ -22,7 +22,7 @@ export class AESEncrypt {
//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 });
console.log('AES encrypt',decrypted.toString());
// console.log('AES encrypt',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 { AESEncrypt } from '../services/aesencrypt.service';
import { CookieService } from 'ngx-cookie-service';
import { WsChatService } from 'src/app/services/chat/ws-chat.service';
@Injectable({
providedIn: 'root'
})
@@ -19,7 +19,9 @@ export class AuthService {
userId$ = new BehaviorSubject<any>('');
headers: HttpHeaders;
public ValidatedUser: UserSession;
public ValidatedUserChat:any;
public wsValidatedUserChat:any;
public ValidatedUserChat:any = {}
public isWsAuthenticated: boolean = false;
opts:any;
constructor(
@@ -29,12 +31,22 @@ export class AuthService {
public alertController: AlertController,
private aesencrypt: AESEncrypt,
private cookieService: CookieService,
) {
private WsChatService: WsChatService) {
this.headers = new HttpHeaders();
if (SessionStore.exist) {
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) {
@@ -76,6 +88,9 @@ export class AuthService {
session.Profile = 'MDGPR'
}
session.Password = user.password
session.RochetChatUser = user.username.split('@')[0]
session.BasicAuthKey = user.BasicAuthKey
SessionStore.reset(session)
@@ -91,24 +106,36 @@ export class AuthService {
}
//Login to rocketChat server
async loginChat(user: UserForm): Promise<boolean> {
async loginChat(user: UserForm) {
let postData = {
"user": user.username,
"password": user.password,
}
console.log(postData);
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');
this.ValidatedUserChat = 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);
return true;
}
else{
-7
View File
@@ -8,7 +8,6 @@ import { environment } from 'src/environments/environment';
import { Storage } from '@ionic/storage';
import { Message } from 'src/app/models/message.model';
import { Observable, Subject } from "rxjs/Rx";
import { WebsocketService } from './websocket.service';
@Injectable({
providedIn: 'root'
@@ -31,7 +30,6 @@ export class ChatService {
private authService: AuthService,
private storage: Storage,
private storageService:StorageService,
//private wsService: WebsocketService,
)
{
this.loggedUserChat = authService.ValidatedUserChat;
@@ -42,11 +40,6 @@ export class ChatService {
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){
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ChatUserService } from './chat-user.service';
describe('ChatUserService', () => {
let service: ChatUserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ChatUserService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,9 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ChatUserService {
constructor() { }
}
@@ -1,13 +1,13 @@
import { TestBed } from '@angular/core/testing';
import { MethodsService } from './methods.service';
import { MessageService } from './message.service';
describe('MethodsService', () => {
let service: MethodsService;
describe('MessageService', () => {
let service: MessageService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MethodsService);
service = TestBed.inject(MessageService);
});
it('should be created', () => {
+44
View File
@@ -0,0 +1,44 @@
import { Injectable } from '@angular/core';
import { Message } from 'src/app/models/chatMethod';
import { chatHistory, ChatMessage, File } from 'src/app/models/chatMethod'
@Injectable({
providedIn: 'root'
})
export class MessageService {
customFields
channels = []
mentions = []
msg = ''
rid = ''
ts = {}
u = {}
t = ''
_id =''
_updatedAt = {}
file
attachments
constructor() { }
setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments}:Message) {
this.customFields = customFields
this.channels = channels
this.mentions = mentions
this.msg = msg
this.rid = rid
this.ts = ts
this.u = u
this.t = t
this._id = _id
this._updatedAt = _updatedAt
this.file = file
this.attachments = attachments
}
delete() {}
showDateDuration() {}
}
-11
View File
@@ -1,11 +0,0 @@
import { Injectable } from '@angular/core';
import { ChatService } from '../chat.service';
@Injectable({
providedIn: 'root'
})
export class MethodsService {
constructor(private chatService: ChatService) {
}
}
@@ -1,13 +1,13 @@
import { TestBed } from '@angular/core/testing';
import { SynchroService } from './synchro.service';
import { RoomService } from './room.service';
describe('SynchroService', () => {
let service: SynchroService;
describe('RoomService', () => {
let service: RoomService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(SynchroService);
service = TestBed.inject(RoomService);
});
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 */
+52 -18
View File
@@ -10,9 +10,7 @@ export class ToastService {
constructor(
public toastController: ToastController,
private animationController: AnimationController,
private modalController: ModalController,
) { }
) { }
ngOnInit() {}
@@ -26,7 +24,7 @@ export class ToastService {
async _successMessage(message?: any, callback?) {
let notification = document.createElement('div')
notification.className = 'notification'
notification.innerHTML = `
@@ -36,7 +34,7 @@ export class ToastService {
<ion-icon slot="end" class="title-icon pr-10" src="/assets/images/nofitication-success.svg"></ion-icon>
<p class="text">{{ message }}</p>
</p>
</div>
`
@@ -54,7 +52,7 @@ export class ToastService {
},1000)
},6000)
}
async _badRequest(message?: string, callback?) {
@@ -68,7 +66,7 @@ export class ToastService {
<ion-icon slot="end" class="title-icon pr-10" src="/assets/images/notification-error.svg"></ion-icon>
<p class="text">{{ message }}</p>
</p>
</div>
`
@@ -91,8 +89,41 @@ 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?) {
let notification = document.createElement('div')
notification.className = 'notification'
notification.innerHTML = `
@@ -102,7 +133,7 @@ export class ToastService {
<ion-icon slot="end" class="title-icon pr-10" src="/assets/images/nofitication-success.svg"></ion-icon>
<p class="text">{{ message }}</p>
</p>
</div>
`
@@ -120,7 +151,7 @@ export class ToastService {
},1000)
},6000)
}
async badRequest(message?: string, callback?) {
@@ -134,7 +165,7 @@ export class ToastService {
<ion-icon slot="end" class="title-icon pr-10" src="/assets/images/notification-error.svg"></ion-icon>
<p class="text">{{ message }}</p>
</p>
</div>
`
@@ -157,9 +188,9 @@ export class ToastService {
}
async notificationMessage(message?: any, callback?: any,data?: any) {
let notification = document.createElement('div')
notification.className = 'notificationPush'
notification.innerHTML = `
@@ -168,7 +199,7 @@ export class ToastService {
<p class="message d-flex align-left">
<p class="text">{{ message }}</p>
</p>
</div>
`
@@ -191,7 +222,7 @@ export class ToastService {
},1000)
},6000)
}
@@ -218,15 +249,18 @@ export class ToastService {
</div>
</div>
`;
console.log(document.querySelector('body').classList)
// console.log(document.querySelector('body').classList)
document.body.append(loader)
loader.addEventListener('click', ()=>{
// loader.remove()
})
return loader
}
}
export const ToastsService = new ToastService(new ToastController())
+5 -2
View File
@@ -1,5 +1,6 @@
import { Injectable } from '@angular/core';
import * as Rx from "rxjs/Rx";
import { Observable, Subject } from "rxjs/Rx";
@Injectable({
providedIn: 'root'
@@ -7,11 +8,13 @@ import * as Rx from "rxjs/Rx";
export class WebsocketService {
message = '';
messages = [];
public messages: Subject<any>;
currentUser = '';
private subject: Rx.Subject<MessageEvent>;
constructor() { }
constructor() {
console.log("CHAT WEBSOCKET");
}
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {