mirror of
https://code.equilibrium.co.ao/ITO/doneit-web.git
synced 2026-04-20 21:35:50 +00:00
merge chat
This commit is contained in:
@@ -1,8 +1,25 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpService } from 'src/app/services/http.service';
|
||||
import { UserListOutOutDTO } from '../DTO/userListOutput';
|
||||
import { ContactCombinedOutputDTO, EventListDataOutputDTOSchema } from '../DTO/contactsCombined';
|
||||
import { APIReturn } from 'src/app/services/decorator/api-validate-schema.decorator';
|
||||
import { HttpService } from 'src/app/services/http.service';
|
||||
import { ContactCombinedOutputDTO, EventListDataOutputDTOSchema } from '../DTO/contactsCombined';
|
||||
|
||||
export interface UserContacts {
|
||||
wxUserId: number;
|
||||
wxFullName: string;
|
||||
wxeMail: string | null;
|
||||
userPhoto: string | null;
|
||||
}
|
||||
|
||||
export interface UserListResult {
|
||||
total: number,
|
||||
result: UserContacts[]
|
||||
}
|
||||
|
||||
export interface UserList {
|
||||
success: boolean;
|
||||
message: string;
|
||||
data: UserListResult;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
@@ -14,13 +31,13 @@ export class ContactsDataSourceService {
|
||||
constructor(private httpService: HttpService) {}
|
||||
|
||||
|
||||
async getUsers() {
|
||||
return await this.httpService.get<UserList>(`${this.baseUrl}/Users`);
|
||||
}
|
||||
|
||||
|
||||
@APIReturn(EventListDataOutputDTOSchema, '/Contacts/Combined')
|
||||
async getCombinedList() {
|
||||
return await this.httpService.get<ContactCombinedOutputDTO>(`${this.baseUrl}/Contacts/Combined`);
|
||||
}
|
||||
|
||||
async getUsers() {
|
||||
return await this.httpService.get<UserListOutOutDTO>(`${this.baseUrl}/Users`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { HttpErrorResponse } from "@angular/common/http";
|
||||
import { Result } from "neverthrow";
|
||||
import { ZodError } from "zod";
|
||||
|
||||
export type DataSourceReturn<T> = Promise<Result<T, HttpErrorResponse | ZodError>>
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { AlertController, AnimationController } from '@ionic/angular';
|
||||
import { ChatSystemService } from './chat/chat-system.service';
|
||||
// import { ChatSystemService } from './chat/chat-system.service';
|
||||
import { ToastService } from './toast.service';
|
||||
|
||||
@Injectable({
|
||||
@@ -12,7 +12,7 @@ export class AlertService {
|
||||
public alertController: AlertController,
|
||||
private animationController: AnimationController,
|
||||
private toastService: ToastService,
|
||||
public ChatSystemService: ChatSystemService,
|
||||
// public ChatSystemService: ChatSystemService,
|
||||
) { }
|
||||
|
||||
async presentAlert(message:string) {
|
||||
@@ -58,9 +58,9 @@ export class AlertService {
|
||||
handler: () => {
|
||||
//const loader = this.toastService.loading();
|
||||
|
||||
this.ChatSystemService.deleteMessage(msgId).then(() => {
|
||||
room.deleteMessage(msgId)
|
||||
}).catch((error) => console.error(error))
|
||||
// this.ChatSystemService.deleteMessage(msgId).then(() => {
|
||||
// room.deleteMessage(msgId)
|
||||
// }).catch((error) => console.error(error))
|
||||
//this.ChatSystemService.subscribeToRoomUpdate(room._id, room);
|
||||
//loader.remove();
|
||||
}
|
||||
|
||||
@@ -7,20 +7,19 @@ import { BehaviorSubject, of } from 'rxjs';
|
||||
import { AlertController, Platform } from '@ionic/angular';
|
||||
import { SessionStore } from '../store/session.service';
|
||||
import { AESEncrypt } from '../services/aesencrypt.service';
|
||||
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service';
|
||||
// import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service';
|
||||
import { Router } from '@angular/router';
|
||||
import { NfService } from 'src/app/services/chat/nf.service';
|
||||
import { MessageService } from 'src/app/services/chat/message.service';
|
||||
// import { NfService } from 'src/app/services/chat/nf.service';
|
||||
//import { MessageService } from 'src/app/services/chat/message.service';
|
||||
import { ProcessesService } from 'src/app/services/processes.service';
|
||||
import { AttachmentsService } from 'src/app/services/attachments.service';
|
||||
import { RoomService } from './chat/room.service';
|
||||
//import { RoomService } from './chat/room.service';
|
||||
import { Storage } from '@ionic/storage';
|
||||
import { InitialsService } from './functions/initials.service';
|
||||
import { PermissionService } from './permission.service';
|
||||
import { ChatSystemService } from 'src/app/services/chat/chat-system.service';
|
||||
// import { ChatSystemService } from 'src/app/services/chat/chat-system.service';
|
||||
import { HttpErrorHandle } from 'src/app/services/http-error-handle.service';
|
||||
import { captureException } from '@sentry/angular';
|
||||
import { CPSession } from '../store/documentManagement';
|
||||
import { catchError, tap } from 'rxjs/operators';
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
@@ -40,15 +39,15 @@ export class AuthService {
|
||||
private storageService: StorageService,
|
||||
public alertController: AlertController,
|
||||
private aesencrypt: AESEncrypt,
|
||||
private RochetChatConnectorService: RochetChatConnectorService,
|
||||
// private RochetChatConnectorService: RochetChatConnectorService,
|
||||
private router: Router,
|
||||
private NfService: NfService,
|
||||
// private NfService: NfService,
|
||||
private processesService: ProcessesService,
|
||||
private AttachmentsService: AttachmentsService,
|
||||
private storage: Storage,
|
||||
private initialsService: InitialsService,
|
||||
public p: PermissionService,
|
||||
public ChatSystemService: ChatSystemService,
|
||||
// public ChatSystemService: ChatSystemService,
|
||||
private httpErroHandle: HttpErrorHandle,
|
||||
private errorHandler: ErrorHandler,
|
||||
private platform: Platform,) {
|
||||
@@ -183,110 +182,63 @@ export class AuthService {
|
||||
setTimeout(() => {
|
||||
|
||||
if (SessionStore.user.ChatData?.data) {
|
||||
this.RochetChatConnectorService.logout();
|
||||
this.RochetChatConnectorService.connect();
|
||||
this.RochetChatConnectorService.login().then((message: any) => {
|
||||
// console.log('Chat login', message)
|
||||
// this.RochetChatConnectorService.logout();
|
||||
// this.RochetChatConnectorService.connect();
|
||||
// this.RochetChatConnectorService.login().then((message: any) => {
|
||||
// console.log('Chat login', message)
|
||||
|
||||
SessionStore.user.RochetChatUserId = message.result.id
|
||||
SessionStore.save()
|
||||
// SessionStore.user.RochetChatUserId = message.result.id
|
||||
// SessionStore.save()
|
||||
|
||||
this.ChatSystemService.loadChat()
|
||||
this.RochetChatConnectorService.setStatus('online')
|
||||
window['RochetChatConnectorService'] = this.RochetChatConnectorService
|
||||
setTimeout(() => {
|
||||
this.ChatSystemService.getAllRooms();
|
||||
this.RochetChatConnectorService.setStatus('online')
|
||||
}, 200);
|
||||
// this.ChatSystemService.loadChat()
|
||||
// this.RochetChatConnectorService.setStatus('online')
|
||||
// window['RochetChatConnectorService'] = this.RochetChatConnectorService
|
||||
// setTimeout(() => {
|
||||
// this.ChatSystemService.getAllRooms();
|
||||
// this.RochetChatConnectorService.setStatus('online')
|
||||
// }, 200);
|
||||
|
||||
|
||||
}).catch((error) => {
|
||||
console.error(SessionStore.user.ChatData, 'web socket login', error)
|
||||
// }).catch((error) => {
|
||||
// console.error(SessionStore.user.ChatData, 'web socket login', error)
|
||||
|
||||
if(window.location.pathname.includes('/home/')) {
|
||||
setTimeout(() => {
|
||||
this.loginToChatWs();
|
||||
}, 4000)
|
||||
}
|
||||
// if(window.location.pathname.includes('/home/')) {
|
||||
// setTimeout(() => {
|
||||
// this.loginToChatWs();
|
||||
// }, 4000)
|
||||
// }
|
||||
|
||||
})
|
||||
// })
|
||||
}
|
||||
|
||||
|
||||
|
||||
// before sending a message with a attachment
|
||||
this.NfService.beforeSendAttachment = async (message: MessageService, room?: RoomService) => {
|
||||
8
|
||||
// this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => {
|
||||
|
||||
if (message.hasFile) {
|
||||
if (message.file.type != 'application/webtrix') {
|
||||
const formData = message.temporaryData
|
||||
// //
|
||||
// let downloadFile = "";
|
||||
// if (message.file.type == "application/img") {
|
||||
// const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise();
|
||||
|
||||
try {
|
||||
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
|
||||
message.file.guid = guid.path
|
||||
// if (event.type === HttpEventType.DownloadProgress) {
|
||||
// //this.downloadProgess = Math.round((100 * event.loaded) / event.total);
|
||||
// return true
|
||||
// } else if (event.type === HttpEventType.Response) {
|
||||
// downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
|
||||
|
||||
message.downloadFileMsg()
|
||||
message.uploadingFile = false
|
||||
// message.file = {
|
||||
// guid: message.file.guid,
|
||||
// image_url: downloadFile,
|
||||
// type: message.file.type
|
||||
// }
|
||||
|
||||
return true
|
||||
} catch (e) {
|
||||
window['e'] = e
|
||||
console.error('BeforesendAtachment', e)
|
||||
message.uploadingFile = false
|
||||
this.httpErroHandle.httpStatusHandleUploadFile(e);
|
||||
return false
|
||||
}
|
||||
|
||||
} else {
|
||||
try {
|
||||
const res = message.temporaryData
|
||||
|
||||
let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
|
||||
|
||||
let url_no_options: string = url.replace("webTRIX.Viewer", "webTRIX.Viewer.Branch1");
|
||||
message.attachments[0].title_link = url_no_options
|
||||
message.attachments[0].message_link = url_no_options
|
||||
|
||||
message.uploadingFile = false
|
||||
|
||||
return true
|
||||
} catch (e) {
|
||||
window['e'] = e
|
||||
console.error('BeforesendAtachment', e)
|
||||
message.uploadingFile = false
|
||||
this.httpErroHandle.httpStatusHandleUploadFile(e);
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => {
|
||||
|
||||
//
|
||||
let downloadFile = "";
|
||||
if (message.file.type == "application/img") {
|
||||
const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise();
|
||||
|
||||
if (event.type === HttpEventType.DownloadProgress) {
|
||||
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
|
||||
return true
|
||||
} else if (event.type === HttpEventType.Response) {
|
||||
downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
|
||||
|
||||
message.file = {
|
||||
guid: message.file.guid,
|
||||
image_url: downloadFile,
|
||||
type: message.file.type
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
};
|
||||
// return true
|
||||
// }
|
||||
// return false
|
||||
// }
|
||||
// };
|
||||
|
||||
}, 1)
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { CacheServiceService } from './cache-service.service';
|
||||
|
||||
describe('CacheServiceService', () => {
|
||||
let service: CacheServiceService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(CacheServiceService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,435 +0,0 @@
|
||||
import { HttpHeaders, HttpParams } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpService } from './http.service';
|
||||
import { StorageService } from './storage.service';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { environment } from 'src/environments/environment';
|
||||
import { Storage } from '@ionic/storage';
|
||||
import { PermissionService } from './permission.service';
|
||||
import { SessionStore } from '../store/session.service';
|
||||
import { ChangeProfileService } from 'src/app/services/change-profile.service';
|
||||
import { NetworkServiceService , ConnectionStatus} from 'src/app/services/network-service.service';
|
||||
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ChatService {
|
||||
headers: HttpHeaders;
|
||||
options: any;
|
||||
options1: any;
|
||||
X_User_Id: any;
|
||||
X_Auth_Token: any;
|
||||
loggedUserChat: any;
|
||||
bindOnMessage: any;
|
||||
|
||||
constructor(
|
||||
private http: HttpClient,
|
||||
private httpService: HttpService,
|
||||
private storage: Storage,
|
||||
private storageService: StorageService,
|
||||
public p: PermissionService,
|
||||
private changeProfileService: ChangeProfileService,
|
||||
private NetworkServiceService: NetworkServiceService,
|
||||
private RochetChatConnectorService: RochetChatConnectorService) {
|
||||
|
||||
this.changeProfileService.registerCallback(() => {
|
||||
this.setheader();
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
getDocumentDetails(url: string) {
|
||||
let headersc = new HttpHeaders();
|
||||
headersc = headersc.set('X-User-Id', SessionStore.user.ChatData.data.userId);
|
||||
headersc = headersc.set('X-Auth-Token', SessionStore.user.ChatData.data.authToken);
|
||||
headersc = headersc.set('Sec-Fetch-Dest', 'attachment');
|
||||
headersc = headersc.set('Sec-Fetch-Mode', 'navigate');
|
||||
headersc = headersc.set('Cookie', 'rc_uid=fsMwcNdufWvdnChj7');
|
||||
headersc = headersc.set('Cookie', 'rc_token=MLbhikLQI4xo9_vL43HqheKPPbxjag7hKfwxe9AjcvY');
|
||||
// headersc = headersc.set("Host", "www.tabularium.pt");
|
||||
// headersc = headersc.set("Origin", "http://localhost:8100");
|
||||
headersc = headersc.set('Referer', 'http://localhost:8100/');
|
||||
let optionsc = {
|
||||
headers: headersc,
|
||||
withCredentials: true
|
||||
};
|
||||
// let fullUrl = "https://www.tabularium.pt/" + url;
|
||||
return this.http.get(url, optionsc).subscribe(() => {
|
||||
// this.fileService.viewDocumentByUrl(url)
|
||||
});
|
||||
}
|
||||
|
||||
getAllChannels() {
|
||||
return this.http.get(environment.apiChatUrl + 'channels.list', this.options);
|
||||
}
|
||||
|
||||
getAllUserChannels() {
|
||||
return this.http.get(environment.apiChatUrl + 'channels.list.joined', this.options);
|
||||
}
|
||||
|
||||
getAllRooms() {
|
||||
return this.http.get(environment.apiChatUrl + 'rooms.get', this.options);
|
||||
}
|
||||
|
||||
getRoomInfo(roomId: any) {
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'rooms.info', opts);
|
||||
}
|
||||
|
||||
|
||||
GetSubscriptionRoomUnreadM(roomId) {
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'subscriptions.getOne', opts);
|
||||
}
|
||||
|
||||
getChannelInfo(roomId: any) {
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
params = params.set("unread", "true");
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'rooms.info', opts);
|
||||
}
|
||||
|
||||
customsRooms(params: any) {
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'rooms.get', opts);
|
||||
}
|
||||
getAllPrivateGroups() {
|
||||
return this.http.get(environment.apiChatUrl + 'groups.list', this.options);
|
||||
}
|
||||
|
||||
getAllUsers() {
|
||||
return this.http.get(environment.apiChatUrl + 'users.list', this.options);
|
||||
}
|
||||
getAllConnectedUsers() {
|
||||
return this.http.get(environment.apiChatUrl + 'users.presence', this.options);
|
||||
}
|
||||
|
||||
//Load messages from roomId
|
||||
getAllDirectMessages() {
|
||||
return this.http.get(environment.apiChatUrl + 'im.list', this.options);
|
||||
}
|
||||
//Load messages from roomId
|
||||
getRoomMessages(roomId: any) {
|
||||
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params,
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'im.history', opts);
|
||||
}
|
||||
|
||||
sendMessage(body: any) {
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
}
|
||||
return this.http.post(environment.apiChatUrl + 'chat.sendMessage', body, opts);
|
||||
}
|
||||
|
||||
uploadFile(formData: any, rid: string) {
|
||||
let url = environment.apiChatUrl + 'rooms.upload/' + rid;
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
}
|
||||
return this.http.post(url, formData, opts);
|
||||
}
|
||||
|
||||
deleteMessage(body: any) {
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
}
|
||||
return this.http.post(environment.apiChatUrl + 'chat.delete', body, opts);
|
||||
}
|
||||
|
||||
leaveRoom(body: any) {
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
}
|
||||
return this.http.post(environment.apiChatUrl + 'rooms.leave', body, opts);
|
||||
}
|
||||
//Load members from a chat
|
||||
getMembers(roomId: any) {
|
||||
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'im.members', opts);
|
||||
}
|
||||
|
||||
getMemberInfo(userId: string) {
|
||||
let params = new HttpParams();
|
||||
params = params.set("userId", userId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'users.info', opts);
|
||||
}
|
||||
|
||||
setUserStatus(body: any) {
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
}
|
||||
return this.http.post(environment.apiChatUrl + 'users.setStatus', body, this.options);
|
||||
}
|
||||
|
||||
removeChatRoom(body: any) {
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
}
|
||||
return this.http.post(environment.apiChatUrl + 'im.delete', body, this.options);
|
||||
}
|
||||
|
||||
createRoom(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'im.create', body, this.options);
|
||||
}
|
||||
getDirectMessage(roomId: string) {
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'im.messages', opts);
|
||||
}
|
||||
|
||||
/* GROUPS */
|
||||
addGroup(body: any) {
|
||||
|
||||
return this.http.post(environment.apiChatUrl + 'groups.create', body, this.options);
|
||||
}
|
||||
setGroupCustomFields(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'groups.setCustomFields', body, this.options);
|
||||
}
|
||||
|
||||
getGroupMembers(roomId: string) {
|
||||
let params = new HttpParams();
|
||||
let url = environment.apiChatUrl + 'groups.members';
|
||||
params = params.set("roomId", roomId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(url, opts);
|
||||
}
|
||||
|
||||
getChannelMembers(roomId: string) {
|
||||
let params = new HttpParams();
|
||||
let url = environment.apiChatUrl + 'channels.members';
|
||||
params = params.set("roomId", roomId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(url, opts);
|
||||
}
|
||||
/* GROUP MESSAGES */
|
||||
getPrivateGroupMessages(roomId: any) {
|
||||
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'groups.history', opts);
|
||||
}
|
||||
getPublicGroupMessages(roomId: any) {
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'channels.history', opts);
|
||||
}
|
||||
closeGroup(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'groups.close', body, this.options);
|
||||
}
|
||||
closeChannel(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'channels.close', body, this.options);
|
||||
}
|
||||
leaveGroup(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'groups.leave', body, this.options);
|
||||
}
|
||||
leaveChannel(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'channels.leave', body, this.options);
|
||||
}
|
||||
removeChannelMember(body: any) {
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
}
|
||||
return this.http.post(environment.apiChatUrl + 'channels.kick', body, opts);
|
||||
}
|
||||
|
||||
addChannelOwner(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'channels.addOwner', body, this.options);
|
||||
}
|
||||
|
||||
addGroupOwner(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'groups.addOwner', body, this.options);
|
||||
}
|
||||
|
||||
deleteGroup(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'groups.delete', body, this.options);
|
||||
}
|
||||
|
||||
deleteChannel(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'channels.delete', body, this.options);
|
||||
}
|
||||
addUserToGroup(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'groups.invite', body, this.options);
|
||||
}
|
||||
getGroupInfo(roomId: any) {
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
return this.http.get(environment.apiChatUrl + 'groups.info', opts);
|
||||
}
|
||||
renameGroup(body: any) {
|
||||
return this.http.post(environment.apiChatUrl + 'groups.rename', body, this.options);
|
||||
}
|
||||
removeGroupMember(body: any) {
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
}
|
||||
return this.http.post(environment.apiChatUrl + 'groups.kick', body, opts);
|
||||
}
|
||||
|
||||
async subscribe(roomId: any) {
|
||||
|
||||
let params = new HttpParams();
|
||||
params = params.set("roomId", roomId);
|
||||
let opts = {
|
||||
headers: this.headers,
|
||||
params: params
|
||||
}
|
||||
|
||||
this.http.get(environment.apiChatUrl + 'im.messages', opts).subscribe(async res => {
|
||||
|
||||
|
||||
if (res == 502) {
|
||||
// Connection timeout
|
||||
// happens when the connection was pending for too long
|
||||
// let's reconnect
|
||||
await this.subscribe(roomId);
|
||||
} else if (res != 200) {
|
||||
// Show Error
|
||||
//showMessage(response.statusText);
|
||||
this.getRoomMessages(roomId)
|
||||
// Reconnect in one second
|
||||
await new Promise(resolve => setTimeout(resolve, 1000)).catch ((error) => {
|
||||
console.error(error);
|
||||
});
|
||||
await this.subscribe(roomId);
|
||||
} else {
|
||||
// Got message
|
||||
//let message = await response.text();
|
||||
this.getRoomMessages(roomId)
|
||||
await this.subscribe(roomId);
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
|
||||
}
|
||||
|
||||
setheader() {
|
||||
try {
|
||||
|
||||
if (this.p.userPermission(this.p.permissionList.Chat.access) && SessionStore.user.ChatData) {
|
||||
this.headers = new HttpHeaders();;
|
||||
|
||||
if (this.p.userPermission(this.p.permissionList.Chat.access)) {
|
||||
//
|
||||
this.headers = this.headers.set('X-User-Id', SessionStore.user.ChatData.data.userId);
|
||||
this.headers = this.headers.set('X-Auth-Token', SessionStore.user.ChatData.data.authToken);
|
||||
this.options = {
|
||||
headers: this.headers,
|
||||
};
|
||||
|
||||
this.resetTimer();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
async refreshtoken() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
lastUpdateIs10sAgo() {
|
||||
const currentTime: any = new Date();
|
||||
|
||||
const diffTime = Math.abs(currentTime - this.timerEventTriggerDateLastUpdate);
|
||||
|
||||
if(this.timerEventTriggerDateLastUpdate == null) {
|
||||
return true
|
||||
}
|
||||
|
||||
if(diffTime >= 5000) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
|
||||
}
|
||||
|
||||
functionTimer = null;
|
||||
timerEventTriggerDate = null
|
||||
timerEventTriggerDateLastUpdate = null
|
||||
|
||||
resetTimer() {
|
||||
clearTimeout(this.functionTimer);
|
||||
this.timerEventTriggerDate = new Date(+new Date() + 60000*15);
|
||||
|
||||
this.functionTimer = setTimeout(() => {
|
||||
|
||||
if(this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) {
|
||||
this.refreshtoken();
|
||||
} else {
|
||||
this.resetTimer()
|
||||
}
|
||||
|
||||
}, 60000 * 15); // time is in milliseconds
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { ChangeMessageQueueService } from './change-message-queue.service';
|
||||
|
||||
describe('ChangeMessageQueueService', () => {
|
||||
let service: ChangeMessageQueueService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(ChangeMessageQueueService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { ChatMethodsService } from './chat-methods.service';
|
||||
|
||||
describe('ChatMethodsService', () => {
|
||||
let service: ChatMethodsService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(ChatMethodsService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { ChatService } from '../chat.service';
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ChatMethodsService {
|
||||
|
||||
constructor(
|
||||
private chatService: ChatService) {
|
||||
}
|
||||
|
||||
sendMessage(roomId:string, data:any) {
|
||||
|
||||
let body = {
|
||||
"message":
|
||||
{
|
||||
"rid": roomId,
|
||||
"msg":"",
|
||||
"file": {
|
||||
"type": "application/meeting",
|
||||
"subject": data.subject,
|
||||
"start_date": data.start,
|
||||
"end_date": data.end,
|
||||
"venue": data.venue,
|
||||
"id": data.id,
|
||||
"calendarId": data.calendarId
|
||||
}
|
||||
}
|
||||
}
|
||||
this.chatService.sendMessage(body).subscribe(res=> {});
|
||||
}
|
||||
|
||||
send({roomId, msg, attachments = null, file = null, localReference = null}) {
|
||||
|
||||
let body = {
|
||||
"message":
|
||||
{
|
||||
rid: roomId,
|
||||
localReference: localReference,
|
||||
msg: msg,
|
||||
attachments,
|
||||
file
|
||||
}
|
||||
}
|
||||
|
||||
return this.chatService.sendMessage(body)
|
||||
}
|
||||
|
||||
deleteMessage(body) {
|
||||
return this.chatService.deleteMessage(body)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { ChatSystemService } from './chat-system.service';
|
||||
|
||||
describe('ChatSystemService', () => {
|
||||
let service: ChatSystemService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(ChatSystemService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,811 +0,0 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { RoomService } from './room.service';
|
||||
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.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 { Update as room } from 'src/app/models/chatMethod';
|
||||
import { Storage } from '@ionic/storage';
|
||||
import { ModalController, NavController, Platform } from '@ionic/angular';
|
||||
import { SqliteService } from 'src/app/services/sqlite.service';
|
||||
import { ChatService } from 'src/app/services/chat.service';
|
||||
import { NativeNotificationService } from 'src/app/services/native-notification.service';
|
||||
import { SortService } from '../functions/sort.service';
|
||||
import { chatUser } from 'src/app/models/chatMethod';
|
||||
import { NfService } from 'src/app/services/chat/nf.service'
|
||||
import { ChatMethodsService } from './chat-methods.service';
|
||||
import { AESEncrypt } from '../aesencrypt.service'
|
||||
import { AttachmentsService } from 'src/app/services/attachments.service';
|
||||
import { NetworkServiceService } from 'src/app/services/network-service.service';
|
||||
import { ViewedMessageService } from './viewed-message.service'
|
||||
import { NotificationsService } from '../notifications.service';
|
||||
import { Subscribe } from '../subcribe';
|
||||
import { Plugins } from '@capacitor/core';
|
||||
|
||||
const { App } = Plugins;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ChatSystemService {
|
||||
|
||||
dm: { [key: string]: RoomService } = {}
|
||||
group: { [key: string]: RoomService } = {}
|
||||
|
||||
_dm: RoomService[] = []
|
||||
_group: RoomService[] = []
|
||||
|
||||
loadingWholeList = false;
|
||||
|
||||
dmCount = 0;
|
||||
groupCount = 0;
|
||||
|
||||
currentRoom: RoomService = null
|
||||
users: chatUser[] = []
|
||||
sessionStore = SessionStore
|
||||
delete = []
|
||||
loadingUsers = false
|
||||
|
||||
onRoomsLoad = new Subscribe({ execute: false, deleteOnExecute: true })
|
||||
private mainChangeDetector: Function = () => {}
|
||||
|
||||
|
||||
constructor(
|
||||
private RochetChatConnectorService: RochetChatConnectorService,
|
||||
private storage: Storage,
|
||||
private platform: Platform,
|
||||
private sqlservice: SqliteService,
|
||||
private NativeNotificationService: NativeNotificationService,
|
||||
private sortService: SortService,
|
||||
private ChatService: ChatService,
|
||||
private NfService: NfService,
|
||||
private chatService: ChatService,
|
||||
private ChatMethodsService: ChatMethodsService,
|
||||
private AESEncrypt: AESEncrypt,
|
||||
private AttachmentsService: AttachmentsService,
|
||||
private NetworkServiceService: NetworkServiceService,
|
||||
private ViewedMessageService: ViewedMessageService,
|
||||
private notificationService: NotificationsService,
|
||||
private modalController: ModalController,
|
||||
private navController: NavController
|
||||
) {
|
||||
|
||||
|
||||
this.RochetChatConnectorService.registerCallback({
|
||||
type: 'reConnect',
|
||||
funx: async () => {
|
||||
/**
|
||||
* @description when the phone is in the background for a long time it could disconnects from the socket then the socket reconnects automatically,
|
||||
* when the connection is lost the subscribe is also lost, so we have to subscribe again when reconnection is establish.
|
||||
*/
|
||||
|
||||
this.RochetChatConnectorService.setStatus('online')
|
||||
this.getUserStatus();
|
||||
await this.chatService.refreshtoken();
|
||||
this.getUser();
|
||||
this.getAllRooms();
|
||||
this.subscribeToRoom();
|
||||
//
|
||||
|
||||
|
||||
if (this.currentRoom) {
|
||||
this.currentRoom.loadHistory({ forceUpdate: true })
|
||||
}
|
||||
|
||||
for (const id in this.dm) {
|
||||
this.dm[id].hasLoadHistory = false
|
||||
}
|
||||
|
||||
for (const id in this.group) {
|
||||
this.group[id].hasLoadHistory = false
|
||||
}
|
||||
|
||||
}
|
||||
})
|
||||
|
||||
if (this.sessionStore.user.Inactivity) {
|
||||
this.loadChat();
|
||||
}
|
||||
|
||||
|
||||
if (SessionStore.user?.ChatData?.data) {
|
||||
this.restoreRooms();
|
||||
}
|
||||
|
||||
document.addEventListener('resume', () => {
|
||||
this.RochetChatConnectorService.setStatus('online')
|
||||
if (this._dm?.length == 0 && this._group?.length == 0) {
|
||||
if (SessionStore.user?.ChatData?.data) {
|
||||
this.getAllRooms();
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
if (!this.platform.is('desktop')) {
|
||||
App.addListener('appStateChange', ({ isActive }) => {
|
||||
if (isActive) {
|
||||
// The app is in the foreground.
|
||||
console.log('App is in the foreground');
|
||||
|
||||
if (SessionStore.user?.ChatData?.data) {
|
||||
this.currentRoom?.loadHistory({ forceUpdate: true })
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
if (SessionStore.user?.ChatData?.data) {
|
||||
this.subscribeToRoom()
|
||||
this.RochetChatConnectorService.setStatus('online')
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
/* this.reloadComponent(true) */
|
||||
} else {
|
||||
// The app is in the background.
|
||||
console.log('App is in the background');
|
||||
// You can perform actions specific to the background state here.
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch(error) {}
|
||||
}
|
||||
|
||||
loadChat() {
|
||||
if (SessionStore.user?.ChatData?.data) {
|
||||
this.ReLoadChat()
|
||||
}
|
||||
}
|
||||
|
||||
private async ReLoadChat() {
|
||||
|
||||
if (SessionStore.user?.ChatData?.data) {
|
||||
this.getUserStatus();
|
||||
await this.chatService.refreshtoken();
|
||||
|
||||
this.restoreUsers();
|
||||
await this.getUser();
|
||||
await this.restoreRooms();
|
||||
await this.getAllRooms();
|
||||
this.subscribeToRoom();
|
||||
}
|
||||
//
|
||||
|
||||
}
|
||||
|
||||
clearChat() {
|
||||
this.dm = {}
|
||||
this.group = {}
|
||||
this._dm = []
|
||||
this._group = []
|
||||
|
||||
this.loadingWholeList = false;
|
||||
|
||||
this.dmCount = 0;
|
||||
this.groupCount = 0;
|
||||
|
||||
this.currentRoom = null
|
||||
this.users = []
|
||||
this.storage.remove('Users');
|
||||
}
|
||||
|
||||
openRoom(roomId) {
|
||||
|
||||
if (this.currentRoom) {
|
||||
this.currentRoom.roomLeave()
|
||||
}
|
||||
|
||||
if (this.getDmRoom(roomId)) {
|
||||
this.currentRoom = this.getDmRoom(roomId)
|
||||
} else if (this.getGroupRoom(roomId)) {
|
||||
this.currentRoom = this.getGroupRoom(roomId)
|
||||
}
|
||||
|
||||
this.currentRoom.open()
|
||||
|
||||
}
|
||||
|
||||
getRoomById(roomId) {
|
||||
if (this.getDmRoom(roomId)) {
|
||||
return this.getDmRoom(roomId)
|
||||
} else if (this.getGroupRoom(roomId)) {
|
||||
return this.getGroupRoom(roomId)
|
||||
}
|
||||
}
|
||||
|
||||
async restoreRooms() {
|
||||
|
||||
try {
|
||||
const _rooms = await this.storage.get('Rooms');
|
||||
|
||||
if (_rooms) {
|
||||
for (let roomData of this.sortArrayISODate(_rooms)) {
|
||||
await this.prepareRoom(roomData);
|
||||
}
|
||||
}
|
||||
} catch (e) { }
|
||||
|
||||
}
|
||||
|
||||
async restoreUsers() {
|
||||
const users = await this.storage.get('Users');
|
||||
|
||||
if (users) {
|
||||
this.users = users
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
sortArrayISODate(messages: any): any[] {
|
||||
|
||||
return messages.sort((a, b) =>
|
||||
new Date(b._updatedAt).getTime()
|
||||
-
|
||||
new Date(a._updatedAt).getTime())
|
||||
}
|
||||
|
||||
async getAllRooms(callback: Function = () => { }, roomIdCallback = "") {
|
||||
this.loadingWholeList = true
|
||||
var rooms;
|
||||
|
||||
if (this.RochetChatConnectorService.isLogin) {
|
||||
try {
|
||||
rooms = await this.RochetChatConnectorService.getRooms();
|
||||
} catch (error) {
|
||||
this.loadingWholeList = false
|
||||
console.error('chatgetrooms', error)
|
||||
}
|
||||
try {
|
||||
await this.storage.remove('Rooms');
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
let index = 0
|
||||
|
||||
let _rooms = rooms?.result?.update
|
||||
|
||||
if (_rooms) {
|
||||
|
||||
_rooms = _rooms.map(e => {
|
||||
e["_updatedAt"] = e._updatedAt || e._updatedAt['$date']
|
||||
return e
|
||||
})
|
||||
|
||||
for (let roomData of this.sortArrayISODate(_rooms)) {
|
||||
|
||||
const roomId = this.getRoomId(roomData);
|
||||
|
||||
if (roomData.t == 'd') {
|
||||
await this.prepareRoom(roomData);
|
||||
} else {
|
||||
if (roomData.t === 'p') {
|
||||
await this.prepareRoom(roomData);
|
||||
}
|
||||
else {
|
||||
await this.prepareRoom(roomData);
|
||||
}
|
||||
}
|
||||
|
||||
if (roomId == roomIdCallback) {
|
||||
callback()
|
||||
}
|
||||
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
this.loadingWholeList = false
|
||||
this.sortRoomList()
|
||||
await this.storage.set('Rooms', _rooms);
|
||||
|
||||
this.onRoomsLoad.executor()
|
||||
}
|
||||
|
||||
|
||||
async getRoom(_rooms: any) {
|
||||
this.loadingWholeList = true
|
||||
|
||||
let index = 0
|
||||
|
||||
if (_rooms) {
|
||||
|
||||
_rooms = _rooms.map(e => {
|
||||
e["_updatedAt"] = e._updatedAt || e._updatedAt['$date']
|
||||
return e
|
||||
})
|
||||
|
||||
for (let roomData of this.sortArrayISODate(_rooms)) {
|
||||
|
||||
if (roomData.t == 'd') {
|
||||
|
||||
await this.prepareRoom(roomData);
|
||||
} else {
|
||||
if (roomData.t === 'p') {
|
||||
|
||||
await this.prepareRoom(roomData);
|
||||
|
||||
}
|
||||
else {
|
||||
|
||||
await this.prepareRoom(roomData);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
this.loadingWholeList = false
|
||||
this.sortRoomList()
|
||||
|
||||
this.onRoomsLoad.executor()
|
||||
}
|
||||
|
||||
/**
|
||||
* @description sort room list by last message date
|
||||
*/
|
||||
sortRoomList = () => {
|
||||
|
||||
this._dm = this.sortService.sortDate(this._dm, '_updatedAt').reverse()
|
||||
this._group = this.sortService.sortDate(this._group, '_updatedAt').reverse()
|
||||
}
|
||||
|
||||
/**
|
||||
* @description subscribe all room
|
||||
*/
|
||||
subscribeToRoom() {
|
||||
|
||||
if (SessionStore.user?.ChatData?.data) {
|
||||
|
||||
for (const id in this.dm) {
|
||||
this.defaultSubtribe(id)
|
||||
}
|
||||
|
||||
for (const id in this.group) {
|
||||
this.defaultSubtribe(id)
|
||||
}
|
||||
|
||||
this.RochetChatConnectorService.streamNotifyLogged().then((subscription => { }))
|
||||
|
||||
this.RochetChatConnectorService.subStreamMessageUser().then((subscription => {
|
||||
console.log({subscription})
|
||||
}))
|
||||
} else {
|
||||
|
||||
setTimeout(() => {
|
||||
throw ('No chat data');
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @description when a new room is create, needs to subtribe in order to receive updates
|
||||
* @param id
|
||||
* @param roomData
|
||||
*/
|
||||
subscribeToRoomUpdate(id, roomData) {
|
||||
|
||||
this.defaultSubtribe(id);
|
||||
|
||||
this.prepareRoom(roomData);
|
||||
|
||||
this.getGroupRoom(id).loadHistory({});
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated things a room need to subscribe on
|
||||
* @param id room id
|
||||
*/
|
||||
private defaultSubtribe(id: any) {
|
||||
|
||||
const room = this.getRoomById(id);
|
||||
|
||||
if (!room.subscribeAttempt) {
|
||||
|
||||
try {
|
||||
|
||||
room.subscribeAttempt = true;
|
||||
} catch (error) {
|
||||
console.log("error")
|
||||
}
|
||||
|
||||
|
||||
this.RochetChatConnectorService.streamRoomMessages(id).then((subscription) => {
|
||||
room.status.receive.message = true;
|
||||
})
|
||||
|
||||
this.RochetChatConnectorService.subStreamNotifyRoom(id, 'typing', false).then((subscription) => {
|
||||
room.status.receive.typing = true;
|
||||
//
|
||||
})
|
||||
|
||||
this.RochetChatConnectorService.subStreamNotifyRoom(id, 'readMessage', false).then((subscription) => {
|
||||
room.status.receive.readMessage = true;
|
||||
})
|
||||
|
||||
this.RochetChatConnectorService.streamNotifyRoomDeleteMessage(id).then((subscription) => {
|
||||
room.status.receive.deleteMessage = true;
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private fix_updatedAt(message) {
|
||||
if (message.result) {
|
||||
message.result._updatedAt = message.result._updatedAt['$date']
|
||||
} else if (message._updatedAt) {
|
||||
if (message._updatedAt.hasOwnProperty('$date')) {
|
||||
message._updatedAt = message._updatedAt['$date']
|
||||
}
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
/**
|
||||
* @description create a representation of an room in these instance this.dm, this.group ...
|
||||
* @param roomData
|
||||
*/
|
||||
prepareRoom(roomData) {
|
||||
|
||||
|
||||
/**
|
||||
* @description data used to define or create room
|
||||
*/
|
||||
|
||||
|
||||
roomData = this.fix_updatedAt(roomData)
|
||||
const setData = {
|
||||
customFields: roomData.customFields,
|
||||
id: this.getRoomId(roomData),
|
||||
name: this.getRoomName(roomData),
|
||||
t: roomData.t,
|
||||
lastMessage: this.getRoomLastMessage(roomData),
|
||||
_updatedAt: new Date(roomData._updatedAt || roomData._updatedAt['$date']),
|
||||
u: roomData.u || {},
|
||||
members: [],
|
||||
membersExcludeMe: []
|
||||
}
|
||||
|
||||
let roomId = this.getRoomId(roomData);
|
||||
|
||||
let chat = false
|
||||
if (roomData?.usernames) {
|
||||
if (roomData?.usernames?.includes("chat.admin")) {
|
||||
chat = true
|
||||
}
|
||||
}
|
||||
|
||||
if (setData.name != 'Rocket Cat' && setData.name != 'general' && chat == false) {
|
||||
// create room
|
||||
if (!this.roomExist(roomId)) {
|
||||
let room: RoomService = new RoomService(this.RochetChatConnectorService, new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this, this.notificationService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this, this.ViewedMessageService, this.notificationService,this.modalController,this.navController)
|
||||
room.setData(setData)
|
||||
room.receiveMessage()
|
||||
room.getAllUsers = this.getUsers
|
||||
room.receiveMessageDelete();
|
||||
room.sortRoomList = this.sortRoomList
|
||||
room.chatServiceDeleteRoom = this.deleteRoom
|
||||
room.isGroup = !this.isIndividual(roomData)
|
||||
room.info()
|
||||
|
||||
|
||||
// create individual room
|
||||
if (this.isIndividual(roomData)) {
|
||||
|
||||
this.dm[roomId] = room
|
||||
this._dm.push(room)
|
||||
this.dmCount++
|
||||
|
||||
} else {
|
||||
// create group room
|
||||
|
||||
this.group[roomId] = room
|
||||
this._group.push(room)
|
||||
this.groupCount++
|
||||
|
||||
}
|
||||
|
||||
this.defaultSubtribe(roomId)
|
||||
} else {
|
||||
// in this case room is already present, therefor it will only be necessary,
|
||||
// to redefine
|
||||
|
||||
if (this.dm[roomId]) {
|
||||
this.dm[roomId].setData(setData)
|
||||
} else if (this.group[roomId]) {
|
||||
this.group[roomId].setData(setData)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
deleteRoom = (roomId) => {
|
||||
|
||||
this.delete.push(roomId)
|
||||
delete this.group[roomId];
|
||||
this._group = this._group.filter((e) => e.id != roomId);
|
||||
}
|
||||
|
||||
deleteRecently(roomId) {
|
||||
return this.delete.includes(roomId)
|
||||
}
|
||||
|
||||
roomExist(roomId) {
|
||||
return this.dm[roomId]?.id || this.group[roomId]?.id
|
||||
}
|
||||
|
||||
getReceptorName(roomData) {
|
||||
try {
|
||||
return roomData.usernames.find((e) => e != SessionStore.user.UserName)
|
||||
} catch (e) {
|
||||
return '*'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description update user status. this method is called once only
|
||||
* @param id user ID
|
||||
*/
|
||||
private getUserStatus(id?: string) {
|
||||
|
||||
this.RochetChatConnectorService.getUserStatus(async (d) => {
|
||||
|
||||
const userId = d.fields.args[0][0]
|
||||
const username = d.fields.args[0][1]
|
||||
let statusNum = d.fields.args[0][2]
|
||||
|
||||
const statusText = this.statusNumberToText(statusNum)
|
||||
|
||||
for (const user in this.users) {
|
||||
if (this.users[user]._id == userId) {
|
||||
this.users[user].status = statusText
|
||||
}
|
||||
}
|
||||
|
||||
this.getUser()
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
getUserByName(username) {
|
||||
return this.users.find((user) => user.username == username)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description convert rocketchat statues num to readable string
|
||||
* @param text
|
||||
* @returns
|
||||
*/
|
||||
statusNumberToText(text) {
|
||||
if (text == '0') {
|
||||
return "offline"
|
||||
}
|
||||
else if (text == '1') {
|
||||
return "online"
|
||||
}
|
||||
else if (text == '2') {
|
||||
return "away"
|
||||
}
|
||||
else if (text == '3') {
|
||||
return "busy"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
deleteMessage(id?) {
|
||||
return this.RochetChatConnectorService.deleteMessage(id);
|
||||
}
|
||||
|
||||
leaveRoom(id?) {
|
||||
return this.RochetChatConnectorService.leaveRoom(id);
|
||||
}
|
||||
|
||||
async hideRoom(id) {
|
||||
this._dm.forEach((md, index) => {
|
||||
if (md.id == id) {
|
||||
this._dm.splice(index, 1)
|
||||
delete this.dm[id]
|
||||
}
|
||||
});
|
||||
|
||||
this._group.forEach((group, index) => {
|
||||
if (group.id == id) {
|
||||
this._group.splice(index, 1)
|
||||
delete this.group[id]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
hidingRoom(id?) {
|
||||
|
||||
return this.RochetChatConnectorService.hidingRoom(id).then(() => {
|
||||
// this.hideRoom(id)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
addRoomOwner(roomid, userId) {
|
||||
return this.RochetChatConnectorService.addRoomOwner(roomid, userId);
|
||||
}
|
||||
|
||||
createPrivateRoom(groupName, username, customFields) {
|
||||
return this.RochetChatConnectorService.createPrivateRoom(groupName, username, customFields);
|
||||
}
|
||||
|
||||
getDmRoom(id): RoomService {
|
||||
try {
|
||||
return this.dm[id]
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
getGroupRoom(id): RoomService {
|
||||
try {
|
||||
return this.group[id]
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
getRoomName(roomData: room): string {
|
||||
if (this.isIndividual(roomData)) {
|
||||
const names: String[] = roomData.usernames
|
||||
|
||||
|
||||
if (roomData.t == 'd') {
|
||||
|
||||
const username = roomData.usernames.find(e => e != SessionStore.user.UserName)
|
||||
|
||||
try {
|
||||
const firstName = capitalizeTxt(username.split('.')[0])
|
||||
const lastName = capitalizeTxt(username.split('.')[1])
|
||||
|
||||
return firstName + ' ' + lastName
|
||||
} catch (error) {
|
||||
const username = roomData.usernames.find(e => e != SessionStore.user.UserName)
|
||||
|
||||
const firstName = capitalizeTxt(username.split('.')[0])
|
||||
return firstName
|
||||
}
|
||||
|
||||
} else {
|
||||
if (roomData.t === 'p') {
|
||||
return 'Loading'
|
||||
}
|
||||
else {
|
||||
return 'Loading'
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
return roomData.fname
|
||||
}
|
||||
}
|
||||
|
||||
getRoomId(roomData: room) {
|
||||
return roomData._id
|
||||
}
|
||||
|
||||
getRoomLastMessage(roomData: room): any {
|
||||
return roomData.lastMessage
|
||||
}
|
||||
|
||||
private isIndividual(roomData: room) {
|
||||
return !roomData.fname
|
||||
}
|
||||
|
||||
getUsers = () => {
|
||||
return this.users
|
||||
}
|
||||
|
||||
async getUser() {
|
||||
|
||||
this.loadingUsers = true
|
||||
let _res
|
||||
|
||||
try {
|
||||
_res = await this.ChatService.getAllUsers().toPromise();
|
||||
} catch (error) {
|
||||
await this.chatService.refreshtoken();
|
||||
_res = await this.ChatService.getAllUsers().toPromise();
|
||||
}
|
||||
|
||||
let users: chatUser[] = _res['users'].filter(data => data.username != SessionStore.user.UserName);
|
||||
|
||||
users = users.filter((data) => !(data.name == 'Rocket.Cat' || data.name == 'Administrator'))
|
||||
|
||||
const userIds = this.users.map((user) => user._id)
|
||||
|
||||
for (let UserUpdate of users) {
|
||||
if (userIds.includes(UserUpdate._id)) {
|
||||
for (var index = 0; index < this.users.length; index++) {
|
||||
if (UserUpdate._id == this.users[index]._id) {
|
||||
this.users[index] = UserUpdate
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.users.push(UserUpdate)
|
||||
}
|
||||
}
|
||||
|
||||
this.users = this.users.sort((a, b) => {
|
||||
if (a.name < b.name) {
|
||||
return -1;
|
||||
}
|
||||
if (a.name > b.name) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
|
||||
await this.storage.set('Users', this.users);
|
||||
|
||||
this.loadingUsers = false
|
||||
|
||||
}
|
||||
|
||||
getUserOfRoom(roomId) {
|
||||
return this.RochetChatConnectorService.getUserOfRoom(roomId);
|
||||
}
|
||||
|
||||
|
||||
async createGroup(name) {
|
||||
const res: any = await this.createPrivateRoom(name, SessionStore.user.UserName, {});
|
||||
if (res?.result?.rid) {
|
||||
try {
|
||||
await this.getAllRooms();
|
||||
} catch (e) { }
|
||||
return res
|
||||
} else {
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async createGroup__(name, customFields = {}) {
|
||||
const res: any = await this.createPrivateRoom(name, SessionStore.user.UserName, customFields);
|
||||
console.log('room is created', res)
|
||||
if (res?.result?.rid) {
|
||||
try {
|
||||
await this.getAllRooms();
|
||||
return res
|
||||
} catch (e) { }
|
||||
console.log('room is loaded')
|
||||
return res
|
||||
} else {
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
getGroupByName(name) {
|
||||
return this._group.find(e => e.name == name)
|
||||
}
|
||||
|
||||
async waitRoomToCreate(rid): Promise<RoomService> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
let sub;
|
||||
|
||||
sub = this.onRoomsLoad.subscribe(() => {
|
||||
const room = this.getRoomById(rid)
|
||||
if (room) {
|
||||
resolve(room)
|
||||
sub.unSubscribe()
|
||||
}
|
||||
})
|
||||
|
||||
try {
|
||||
await this.getAllRooms();
|
||||
} catch (e) { }
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
searchContact(name, username) {
|
||||
return this.users.find(e => e.name == name || e.username == username)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { MessageService } from './message.service';
|
||||
|
||||
describe('MessageService', () => {
|
||||
let service: MessageService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(MessageService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,25 +0,0 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { MessageService } from './message.service';
|
||||
import { RoomService } from './room.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class NfService {
|
||||
|
||||
beforeSendAttachment = async (message: MessageService, room?: RoomService): Promise<boolean> => new Promise ((resolve, reject)=> (resolve(true)));
|
||||
downloadFileMsg = async (message: MessageService, room?: RoomService): Promise<boolean> => new Promise ((resolve, reject)=> (resolve(true)));
|
||||
|
||||
fix_updatedAt(message) {
|
||||
if (message?.result) {
|
||||
message.result._updatedAt = message.result._updatedAt['$date']
|
||||
} else if(message?._updatedAt) {
|
||||
if(message._updatedAt.hasOwnProperty('$date')) {
|
||||
message._updatedAt = message._updatedAt['$date']
|
||||
}
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
constructor() { }
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { RochetChatConnectorService } from './rochet-chat-connector.service';
|
||||
|
||||
describe('RochetChatConnectorService', () => {
|
||||
let service: RochetChatConnectorService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(RochetChatConnectorService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,961 +0,0 @@
|
||||
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';
|
||||
import { BackgroundService } from '../background.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class RochetChatConnectorService {
|
||||
|
||||
isLogin = false;
|
||||
loginResponse = {}
|
||||
|
||||
constructor(private backgroundservice: BackgroundService,) {
|
||||
}
|
||||
|
||||
reConnect() {
|
||||
|
||||
}
|
||||
|
||||
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, requestId: 'connectMessage' })
|
||||
this.ws.send({ message: { msg: "pong" }, loginRequired: false, requestId: 'connectPong' })
|
||||
|
||||
this.ws.registerCallback({
|
||||
type: 'Onmessage',
|
||||
key: 'ping-pong',
|
||||
funx: (message: any) => {
|
||||
if (message.msg == "ping") {
|
||||
this.ws.send({ message: { msg: "pong" }, loginRequired: false })
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
wsSend({ message, requestId = uuidv4(), loginRequired = true }: send) {
|
||||
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: { email: SessionStore.user.Email },
|
||||
password: SessionStore.user.Password
|
||||
}
|
||||
]
|
||||
}
|
||||
this.ws.send({ message, requestId: 'login', 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
|
||||
|
||||
setTimeout(() => {
|
||||
this.ws.wsMsgQueue()
|
||||
}, 10)
|
||||
|
||||
resolve(message)
|
||||
//
|
||||
}
|
||||
} else {
|
||||
this.isLogin = false
|
||||
//
|
||||
reject(message)
|
||||
}
|
||||
|
||||
reject(message)
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
getRooms(roomOlder = 1480377601) {
|
||||
|
||||
|
||||
//const requestId = uuidv4()
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
readMessage(roomId) {
|
||||
|
||||
//const requestId = uuidv4()
|
||||
const requestId = uuidv4()
|
||||
|
||||
const message = {
|
||||
"msg": "method",
|
||||
"method": "readMessages",
|
||||
"params": [roomId, []],
|
||||
"id": requestId
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
getUserOfRoom(roomId) {
|
||||
|
||||
//const requestId = uuidv4()
|
||||
const requestId = uuidv4()
|
||||
|
||||
const message = {
|
||||
"msg": "method",
|
||||
"method": "getUsersOfRoom",
|
||||
"id": requestId,
|
||||
"params": [
|
||||
roomId,
|
||||
false,
|
||||
{
|
||||
"limit": 100,
|
||||
"skip": 0
|
||||
}]
|
||||
}
|
||||
|
||||
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
|
||||
this.ws.disconnect()
|
||||
}
|
||||
|
||||
// send message to room
|
||||
send({ roomId, msg, attachments = null, file = null, localReference = null }) {
|
||||
|
||||
//const requestId = uuidv4()
|
||||
const requestId = uuidv4()
|
||||
var message = {
|
||||
msg: "method",
|
||||
method: "sendMessage",
|
||||
id: requestId,
|
||||
params: [{
|
||||
rid: roomId,
|
||||
localReference: localReference,
|
||||
msg: msg,
|
||||
attachments,
|
||||
file
|
||||
}]
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
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, requestId })
|
||||
return true
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
updateMessage(messageObject) {
|
||||
|
||||
//const requestId = uuidv4()
|
||||
const requestId = uuidv4()
|
||||
var message = {
|
||||
msg: "method",
|
||||
method: "updateMessage",
|
||||
id: requestId,
|
||||
params: [messageObject]
|
||||
}
|
||||
|
||||
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, requestId })
|
||||
return true
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
leaveRoom(roomId) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
var message = {
|
||||
msg: "method",
|
||||
method: "leaveRoom",
|
||||
id: requestId,
|
||||
params: [
|
||||
roomId,
|
||||
]
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
addRoomOwner(roomId, userId) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
var message = {
|
||||
msg: "method",
|
||||
method: "addRoomOwner",
|
||||
id: requestId,
|
||||
params: [
|
||||
roomId,
|
||||
userId
|
||||
]
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
hidingRoom(roomId) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
var message = {
|
||||
msg: "method",
|
||||
method: "hideRoom",
|
||||
id: requestId,
|
||||
params: [roomId]
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
joinRoom() { }
|
||||
|
||||
deleteMessage(msgId) {
|
||||
//const requestId = uuidv4();
|
||||
const requestId = uuidv4()
|
||||
var message = {
|
||||
msg: "method",
|
||||
method: "deleteMessage",
|
||||
id: requestId,
|
||||
params: [{ "_id": msgId }]
|
||||
}
|
||||
|
||||
this.ws.send({ message, requestId });
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.ws.registerCallback({
|
||||
type: 'Onmessage', funx: (message) => {
|
||||
if (message.id == requestId) {
|
||||
resolve(message)
|
||||
return true
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
createPrivateRoom(groupName, username, customFields) {
|
||||
const requestId = uuidv4()
|
||||
|
||||
var message = {
|
||||
msg: "method",
|
||||
method: "createPrivateGroup",
|
||||
id: requestId,
|
||||
params: [
|
||||
groupName,
|
||||
[username],
|
||||
false,
|
||||
customFields,
|
||||
{
|
||||
"broadcast": false,
|
||||
"encrypted": 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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
sendStreamNotifyRoom(roomId: string, username, event: 'typing', param: any) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
let message = {
|
||||
msg: "method",
|
||||
method: "stream-notify-room",
|
||||
id: requestId,
|
||||
params: [
|
||||
`${roomId}/${event}`,
|
||||
username,
|
||||
param
|
||||
]
|
||||
};
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
subStreamNotifyRoom(roomId: string, event: 'typing' | 'deleteMessage' | 'readMessage', param: any) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
let message = {
|
||||
msg: "sub",
|
||||
id: requestId,
|
||||
name: "stream-notify-room",
|
||||
params: [
|
||||
`${roomId}/${event}`,
|
||||
param
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
if (message.id == requestId || message?.subs?.[0] == requestId) { // same request send
|
||||
resolve(message)
|
||||
return true
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
subStreamNotifyUser(param?: any) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
let message = {
|
||||
msg: "sub",
|
||||
id: requestId,
|
||||
name: "stream-notify-user",
|
||||
params: [
|
||||
`${SessionStore.user.ChatData.data.userId}/notification`,
|
||||
param
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
subStreamMessageUser(param?: any) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
try {
|
||||
let message = {
|
||||
msg: "sub",
|
||||
id: requestId,
|
||||
name: "stream-notify-user",
|
||||
params: [
|
||||
`${SessionStore.user.ChatData.data.userId}/message`,
|
||||
param
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
} catch (error) {
|
||||
throw (SessionStore)
|
||||
}
|
||||
}
|
||||
|
||||
receiveStreamNotifyRoom(funx: Function) {
|
||||
|
||||
this.ws.registerCallback({
|
||||
type: 'Onmessage',
|
||||
funx: (message) => {
|
||||
if (message.collection == "stream-notify-room" && message.msg == 'changed') {
|
||||
funx(message)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
getUserStatus(funx: Function) {
|
||||
this.ws.registerCallback({
|
||||
type: 'Onmessage',
|
||||
funx: (message) => {
|
||||
if (message.msg == 'changed' && message.collection == "stream-notify-logged") {
|
||||
funx(message)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
loadHistory(roomId, limit: number = 50) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
const message = {
|
||||
msg: "method",
|
||||
method: "loadHistory",
|
||||
id: requestId,
|
||||
params: [
|
||||
roomId,
|
||||
null,
|
||||
limit,
|
||||
{
|
||||
"$date": 1480377601
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
this.ws.send({ message, requestId: 'loadHistory' })
|
||||
|
||||
return new Promise<chatHistory>((resolve, reject) => {
|
||||
this.ws.registerCallback({
|
||||
type: 'Onmessage', funx: (message) => {
|
||||
//
|
||||
if (message.id == requestId) { // same request send
|
||||
resolve(message)
|
||||
return true
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
loadHistoryUnread(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: 'loadHistory' })
|
||||
|
||||
return new Promise<chatHistory>((resolve, reject) => {
|
||||
this.ws.registerCallback({
|
||||
type: 'Onmessage', funx: (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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
updateRoomEventss(roomId, collection: string, funx: Function,) {
|
||||
|
||||
this.ws.registerCallback({
|
||||
type: 'Onmessage',
|
||||
funx: (message) => {
|
||||
//
|
||||
|
||||
if (message.msg == 'changed' && message.collection == collection) {
|
||||
if (message.fields.args[0].rid == roomId) {
|
||||
funx(message)
|
||||
}
|
||||
else if (message.fields.eventName == `${roomId}/deleteMessage`) {
|
||||
funx(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
streamRoomMessages(roomId: string) {
|
||||
|
||||
const requestId = "streamRoomMessages" + 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 || message?.subs?.[0] == requestId) { // same request send
|
||||
resolve(message)
|
||||
return true
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
streamNotifyLogged() {
|
||||
|
||||
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) { // same request send
|
||||
resolve(message)
|
||||
return true
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
streamNotifyRoomDeleteMessage(roomId: string) {
|
||||
|
||||
const requestId = uuidv4()
|
||||
|
||||
let message = {
|
||||
"msg": "sub",
|
||||
"id": requestId,
|
||||
"name": "stream-notify-room",
|
||||
"params": [
|
||||
`${roomId}/deleteMessage`,
|
||||
true
|
||||
]
|
||||
};
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
registerCallback(data: wsCallbacksParams) {
|
||||
return this.ws.registerCallback(data)
|
||||
}
|
||||
|
||||
// socket class ==================================================================
|
||||
private socket!: WebSocket;
|
||||
private wsMsgQueue: { [key: string]: msgQueue } = {}
|
||||
private wsCallbacks: { [key: string]: wsCallbacksParams } = {}
|
||||
private wsReconnect = 0
|
||||
|
||||
private n = 0
|
||||
|
||||
ws = {
|
||||
connected: false,
|
||||
registerCallback: (params: wsCallbacksParams) => {
|
||||
|
||||
let id = params.requestId || params.key || uuidv4()
|
||||
//
|
||||
this.wsCallbacks[id] = params
|
||||
this.n++
|
||||
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: async () => {
|
||||
|
||||
|
||||
|
||||
this.ws.connected = true
|
||||
this.backgroundservice.online();
|
||||
|
||||
setTimeout(() => {
|
||||
this.ws.wsMsgQueue()
|
||||
}, 10)
|
||||
console.log('rec conect')
|
||||
|
||||
if (this.wsReconnect >= 1) {
|
||||
for (const [key, value] of Object.entries(this.wsCallbacks)) {
|
||||
if (value.type == 'reConnect') {
|
||||
const dontRepeat = await value.funx()
|
||||
|
||||
if (dontRepeat) {
|
||||
this.n--
|
||||
delete this.wsCallbacks[key]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
this.wsReconnect++;
|
||||
},
|
||||
wsMsgQueue: () => {
|
||||
|
||||
for (const [key, item] of Object.entries(this.wsMsgQueue)) {
|
||||
|
||||
if (item.loginRequired == true && this.isLogin == true) {
|
||||
//
|
||||
this.ws.send(item);
|
||||
delete this.wsMsgQueue[key]
|
||||
} else if (item.loginRequired == false) {
|
||||
//
|
||||
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
|
||||
//
|
||||
//
|
||||
|
||||
this.wsMsgQueue[requestId] = { message, requestId, loginRequired }
|
||||
} else {
|
||||
let messageStr = JSON.stringify(message)
|
||||
this.socket.send(messageStr)
|
||||
}
|
||||
return requestId
|
||||
},
|
||||
|
||||
onmessage: async (event: any) => {
|
||||
|
||||
this.backgroundservice.online();
|
||||
|
||||
const data = JSON.parse(event.data)
|
||||
|
||||
for (const [key, value] of Object.entries(this.wsCallbacks)) {
|
||||
if (value.type == 'Onmessage') {
|
||||
const dontRepeat = await value.funx(data)
|
||||
|
||||
if (dontRepeat) {
|
||||
delete this.wsCallbacks[key]
|
||||
this.n--
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
onclose: async (event: any) => {
|
||||
this.ws.connected = false
|
||||
this.isLogin = false
|
||||
|
||||
|
||||
this.connect()
|
||||
this.login()
|
||||
|
||||
for (const [key, value] of Object.entries(this.wsCallbacks)) {
|
||||
if (value.type == 'Offline') {
|
||||
const dontRepeat = await value.funx()
|
||||
|
||||
if (dontRepeat) {
|
||||
delete this.wsCallbacks[key]
|
||||
this.n--
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
},
|
||||
|
||||
onerror: (event: any) => {
|
||||
|
||||
},
|
||||
disconnect: () => {
|
||||
|
||||
if (this.socket) {
|
||||
this.socket.onopen = (event: any) => { }
|
||||
this.socket.onmessage = (event: any) => { }
|
||||
this.socket.onclose = (event: any) => { }
|
||||
this.socket.onerror = (event: any) => { }
|
||||
this.socket.close()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { RoomService } from './room.service';
|
||||
|
||||
describe('RoomService', () => {
|
||||
let service: RoomService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(RoomService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { ViewedMessageService } from './viewed-message.service';
|
||||
|
||||
describe('ViewedMessageService', () => {
|
||||
let service: ViewedMessageService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(ViewedMessageService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import * as FIFOProcessQueue from 'fifo-process-queue';
|
||||
import { RoomService } from './room.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ViewedMessageService {
|
||||
|
||||
constructor() {
|
||||
}
|
||||
|
||||
viewQueue = FIFOProcessQueue(async ({room, userId, statusNum, statusText}, callback) => {
|
||||
|
||||
if(room.membersExcludeMe?.map) {
|
||||
const membersIds = room.membersExcludeMe.map((user)=> user._id)
|
||||
|
||||
if(membersIds.includes(userId)) {
|
||||
|
||||
if(statusText != 'offline') {
|
||||
room.deleteMessageToReceive(userId)
|
||||
}
|
||||
|
||||
let n = 0
|
||||
for (const message of room.messages) {
|
||||
if(message.online) {
|
||||
for(let id of membersIds) {
|
||||
if(message.addReceived(id)) {
|
||||
n++
|
||||
// setTimeout(async() => {
|
||||
await message.saveChanges()
|
||||
// }, 100 * n)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(function () {
|
||||
callback();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
|
||||
viewReadQueue = FIFOProcessQueue(async ({room}, callback) => {
|
||||
|
||||
const membersIds: string[] = room.membersExcludeMe.map((user)=> user._id)
|
||||
|
||||
let n = 0
|
||||
for (const message of room.messages) {
|
||||
if(message.online) {
|
||||
for(let id of membersIds) {
|
||||
|
||||
if(message.addViewed(id)) {
|
||||
message.addReceived(id)
|
||||
n++
|
||||
// setTimeout(async() => {
|
||||
await message.saveChanges()
|
||||
// }, 100 * n)
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
callback()
|
||||
},100)
|
||||
|
||||
})
|
||||
|
||||
request(room:RoomService, userId, statusNum, statusText) {
|
||||
this.viewQueue.push({room, userId, statusNum, statusText})
|
||||
}
|
||||
|
||||
requestReadAll(room:RoomService) {
|
||||
this.viewReadQueue.push({room})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Result } from 'neverthrow';
|
||||
import { z, ZodError } from 'zod';
|
||||
import * as Sentry from '@sentry/capacitor';
|
||||
import { ColoredLoggerService } from '../logger/colored/service';
|
||||
|
||||
export function APIReturn(schema: z.ZodTypeAny, context: string) {
|
||||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const originalMethod = descriptor.value;
|
||||
|
||||
descriptor.value = async function (...args: any[]) {
|
||||
const result: Result<any, HttpErrorResponse> = await originalMethod.apply(this, args);
|
||||
|
||||
if(result.isOk()) {
|
||||
try {
|
||||
// Validate the result using the provided schema
|
||||
schema.parse(result.value);
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
// If validation fails, throw an error with the details
|
||||
//
|
||||
ColoredLoggerService.error(error.errors, 'API unexpected data structure '+ context)
|
||||
console.error(result.value)
|
||||
// Capture the Zod validation error with additional context
|
||||
Sentry.withScope((scope) => {
|
||||
scope.setTag('APIReturn', 'user');
|
||||
scope.setContext('data', { data: result.value });
|
||||
Sentry.captureException(error);
|
||||
});
|
||||
|
||||
} else {
|
||||
console.log('failed to setup the connection successful')
|
||||
// Throw any other unexpected errors
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log()
|
||||
// result.error.
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
return descriptor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { err } from "neverthrow";
|
||||
import { ColoredLoggerService } from "../logger/colored/service";
|
||||
|
||||
export function captureAndReraiseAsync(taskName: string) {
|
||||
return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const originalMethod = descriptor.value;
|
||||
descriptor.value = async function(...args: any[]) {
|
||||
try {
|
||||
return await originalMethod.apply(this, args);
|
||||
} catch (error) {
|
||||
// Log the error along with taskName
|
||||
ColoredLoggerService.error('Capture error from', taskName, error)
|
||||
console.error(error)
|
||||
// Re-throw the same error
|
||||
return err(error) ;
|
||||
}
|
||||
};
|
||||
return descriptor;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Result } from 'neverthrow';
|
||||
import { z, ZodError } from 'zod';
|
||||
import * as Sentry from '@sentry/capacitor';
|
||||
import { ColoredLoggerService } from '../logger/colored/service';
|
||||
|
||||
export function SocketStreamReturn(schema: z.ZodTypeAny, context: string) {
|
||||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const originalMethod = descriptor.value;
|
||||
|
||||
descriptor.value = async function (...args: any[]) {
|
||||
const result: Result<any, HttpErrorResponse> = await originalMethod.apply(this, args);
|
||||
|
||||
if(result.isOk()) {
|
||||
try {
|
||||
// Validate the result using the provided schema
|
||||
schema.parse(result.value);
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
// If validation fails, throw an error with the details
|
||||
//
|
||||
ColoredLoggerService.error(error.errors, 'socket unexpected data structure '+ context, schema._def.description)
|
||||
|
||||
} else {
|
||||
console.log('failed to setup the SocketStreamReturn successful')
|
||||
// Throw any other unexpected errors
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
return descriptor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { err, ok } from 'neverthrow';
|
||||
import { Schema, ZodError } from 'zod';
|
||||
import { ColoredLoggerService } from '../logger/colored/service';
|
||||
import { TracingType } from '../monitoring/opentelemetry/tracer';
|
||||
|
||||
export function ValidateSchema(schema: Schema) {
|
||||
return (
|
||||
target: unknown,
|
||||
propertyKey: string,
|
||||
descriptor: PropertyDescriptor,
|
||||
) => {
|
||||
const originalMethod = descriptor.value;
|
||||
descriptor.value = function (...args: unknown[]) {
|
||||
try {
|
||||
const model = schema.parse(args[0]);
|
||||
args[0] = model;
|
||||
return originalMethod.apply(this, args);
|
||||
} catch (e) {
|
||||
if (e instanceof ZodError) {
|
||||
// If validation fails, throw an error with the details
|
||||
//
|
||||
ColoredLoggerService.error(e.errors, 'unexpected data structure '+ schema._def.description)
|
||||
|
||||
}
|
||||
return err(e)
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param schema Zod Schema
|
||||
* @param context
|
||||
*/
|
||||
export function SafeValidateSchema(schema: Schema, context: string) {
|
||||
return (
|
||||
target: unknown,
|
||||
propertyKey: string,
|
||||
descriptor: PropertyDescriptor,
|
||||
) => {
|
||||
const originalMethod = descriptor.value;
|
||||
descriptor.value = function (...args: unknown[]) {
|
||||
|
||||
const tracing: TracingType = args[args.length - 1] as any;
|
||||
|
||||
try {
|
||||
const model = schema.parse(args[0]);
|
||||
args[0] = model;
|
||||
return originalMethod.apply(this, args);
|
||||
} catch (e) {
|
||||
if (e instanceof ZodError) {
|
||||
// If validation fails, throw an error with the details
|
||||
//
|
||||
// If validation fails, throw an error with the details
|
||||
console.error('unexpected data structure', context)
|
||||
// Capture the Zod validation error with additional context
|
||||
console.error('Validation failed:', e.errors);
|
||||
|
||||
tracing?.setAttribute?.('APIReturn.error', 'true')
|
||||
|
||||
let i = 0;
|
||||
for(const schema of e.errors) {
|
||||
tracing?.setAttribute?.('map.error.schema-'+i, JSON.stringify(schema))
|
||||
}
|
||||
ColoredLoggerService.error(e.errors, 'socket unexpected data structure '+ context, schema._def.description)
|
||||
console.error(args[0])
|
||||
|
||||
}
|
||||
return originalMethod.apply(this, args);
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
// export function ParamsValidationSchema(schema:Schema, { either = false, context = "" }) {
|
||||
// return (
|
||||
// target: unknown,
|
||||
// propertyKey: string,
|
||||
// descriptor: PropertyDescriptor,
|
||||
// ) => {
|
||||
// const originalMethod = descriptor.value;
|
||||
// descriptor.value = function (...args: unknown[]) {
|
||||
|
||||
// const tracing: TracingType = args[args.length - 1] as any;
|
||||
|
||||
// context = context ? context : tracing?.name;
|
||||
|
||||
// try {
|
||||
// tracing.addEvent("Parameter Validation start")
|
||||
// const model = schema.parse(args[0]);
|
||||
// tracing.addEvent("Parameter Validation end")
|
||||
// args[0] = model;
|
||||
// return originalMethod.apply(this, args);
|
||||
// } catch (e) {
|
||||
// if (e instanceof ZodError) {
|
||||
// // If validation fails, throw an error with the details
|
||||
// // Capture the Zod validation error with additional context
|
||||
|
||||
// tracing?.setAttribute?.('parameter.error', 'true')
|
||||
|
||||
// let i = 0;
|
||||
// for(const schema of e.errors) {
|
||||
// tracing?.setAttribute?.('map.error.schema-'+i, JSON.stringify(schema))
|
||||
// }
|
||||
// ColoredLoggerService.error(e.errors, 'Unexpected data structure '+ context,'..')
|
||||
// console.error(args[0])
|
||||
|
||||
// tracing.addEvent("Validation parameter error")
|
||||
// tracing.hasError("Invalid Parameter")
|
||||
// if(either) {
|
||||
// return err(e)
|
||||
// }
|
||||
|
||||
// }
|
||||
// return originalMethod.apply(this, args);
|
||||
// }
|
||||
// };
|
||||
// };
|
||||
// }
|
||||
|
||||
|
||||
export function ParamsValidation(schema:Schema, args, tracing: TracingType) {
|
||||
try {
|
||||
tracing.addEvent("Parameter Validation start")
|
||||
const model = schema.parse(args);
|
||||
tracing.addEvent("Parameter Validation end")
|
||||
args = model;
|
||||
return ok(true);
|
||||
} catch (e) {
|
||||
if (e instanceof ZodError) {
|
||||
// If validation fails, throw an error with the details
|
||||
// Capture the Zod validation error with additional context
|
||||
let i = 0;
|
||||
for(const schema of e.errors) {
|
||||
tracing?.setAttribute?.('map.error.schema-'+i, JSON.stringify(schema))
|
||||
}
|
||||
|
||||
tracing.log("zod error "+ tracing?.name, {
|
||||
zodError: e
|
||||
})
|
||||
ColoredLoggerService.error(e.errors, 'Unexpected data structure '+ tracing?.name,'..')
|
||||
console.error(args)
|
||||
|
||||
tracing.addEvent("Validation parameter error")
|
||||
tracing.hasError("Invalid Parameter")
|
||||
|
||||
}
|
||||
return err(false)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import { InputFilterDirective } from './input-filter.directive';
|
||||
|
||||
describe('InputFilterDirective', () => {
|
||||
it('should create an instance', () => {
|
||||
const directive = new InputFilterDirective();
|
||||
expect(directive).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import { VisibilityDirective } from './visibility.directive';
|
||||
|
||||
describe('VisibilityDirective', () => {
|
||||
it('should create an instance', () => {
|
||||
const directive = new VisibilityDirective();
|
||||
expect(directive).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import { VisibilityDirective } from './visibility.directive';
|
||||
|
||||
describe('VisibilityDirective', () => {
|
||||
it('should create an instance', () => {
|
||||
const directive = new VisibilityDirective();
|
||||
expect(directive).toBeTruthy();
|
||||
});
|
||||
});
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { NfService } from './nf.service';
|
||||
import { ChatServiceService } from './chat-service.service';
|
||||
|
||||
describe('NfService', () => {
|
||||
let service: NfService;
|
||||
describe('ChatServiceService', () => {
|
||||
let service: ChatServiceService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(NfService);
|
||||
service = TestBed.inject(ChatServiceService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
+3
-2
@@ -3,6 +3,7 @@ import { Injectable } from '@angular/core';
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ChangeMessageQueueService {
|
||||
constructor() {}
|
||||
export class ChatServiceService {
|
||||
|
||||
constructor() { }
|
||||
}
|
||||
@@ -78,12 +78,12 @@ export class FileService {
|
||||
path: IMAGE_DIR,
|
||||
directory: Directory.Data,
|
||||
}).then(result => {
|
||||
|
||||
|
||||
let lastphoto = result.files[result.files.length - 1]
|
||||
resolve(lastphoto)
|
||||
},
|
||||
async (err) => {
|
||||
|
||||
|
||||
reject('ERROR FILE DOSENT EXIST')
|
||||
// Folder does not yet exists!
|
||||
await Filesystem.mkdir({
|
||||
@@ -127,7 +127,7 @@ export class FileService {
|
||||
|
||||
//new method 4
|
||||
async loadFileData(fileName: string) {
|
||||
|
||||
|
||||
// for (let f of fileNames) {
|
||||
const filePath = `${IMAGE_DIR}/${fileName}`;
|
||||
|
||||
@@ -139,7 +139,7 @@ export class FileService {
|
||||
data: `data:image/jpeg;base64,${readFile.data}`,
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
const capturedImage = image.data
|
||||
|
||||
@@ -150,9 +150,7 @@ export class FileService {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
getFileFromDevice(types: typeof FileType[]) {
|
||||
getFileFromDevice(types: typeof FileType[]): Promise<File> {
|
||||
const input = this.fileLoaderService.createInput({
|
||||
accept: types
|
||||
})
|
||||
@@ -168,9 +166,6 @@ export class FileService {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
getFileFromDeviceBase64(types: typeof FileType[]) {
|
||||
const input = this.fileLoaderService.createInput({
|
||||
accept: types
|
||||
@@ -199,7 +194,7 @@ export class FileService {
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
viewDocumentByUrl(url) {
|
||||
const browser = this.iab.create(url,"_parent");
|
||||
@@ -254,8 +249,8 @@ export class FileService {
|
||||
dataURLtoFile(dataurl, filename) {
|
||||
var arr = dataurl.split(','),
|
||||
mime = arr[0].match(/:(.*?);/)[1],
|
||||
bstr = atob(arr[arr.length - 1]),
|
||||
n = bstr.length,
|
||||
bstr = atob(arr[arr.length - 1]),
|
||||
n = bstr.length,
|
||||
u8arr = new Uint8Array(n);
|
||||
while(n--){
|
||||
u8arr[n] = bstr.charCodeAt(n);
|
||||
@@ -267,11 +262,11 @@ export class FileService {
|
||||
contentType = contentType || '';
|
||||
const byteCharacters = atob(base64Data);
|
||||
const byteArray = new Uint8Array(byteCharacters.length);
|
||||
|
||||
|
||||
for (let i = 0; i < byteCharacters.length; i++) {
|
||||
byteArray[i] = byteCharacters.charCodeAt(i);
|
||||
}
|
||||
|
||||
|
||||
return new Blob([byteArray], { type: contentType });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { ChatService } from '../chat.service';
|
||||
import { ChatSystemService } from '../chat/chat-system.service';
|
||||
// import { ChatSystemService } from '../chat/chat-system.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
@@ -9,8 +8,10 @@ export class TimeService {
|
||||
countDownTime: any;
|
||||
room: any;
|
||||
|
||||
constructor(private chatService: ChatService,
|
||||
public ChatSystemService: ChatSystemService,) { }
|
||||
constructor(
|
||||
//private chatService: ChatService,
|
||||
//public ChatSystemService: ChatSystemService,
|
||||
) { }
|
||||
|
||||
showDateDuration(start:any) {
|
||||
let end;
|
||||
@@ -42,7 +43,7 @@ export class TimeService {
|
||||
}
|
||||
|
||||
countDownDate(date:any, roomId:string){
|
||||
|
||||
|
||||
let difference = new Date(date).getTime() - new Date().getTime();
|
||||
let c_day = Math.floor(difference/(1000*60*60*24));
|
||||
let c_hours = Math.floor((difference % (1000*60*60*24)) / (1000*60*60));
|
||||
@@ -55,22 +56,22 @@ export class TimeService {
|
||||
|
||||
this.countDownTime = "Expired";
|
||||
let body = { "roomId":roomId, }
|
||||
this.chatService.getRoomInfo(roomId).subscribe(room=>{
|
||||
this.room = room['room'];
|
||||
// this.chatService.getRoomInfo(roomId).subscribe(room=>{
|
||||
// this.room = room['room'];
|
||||
|
||||
if(this.room.t === 'p'){
|
||||
this.chatService.deleteGroup(body).subscribe(res=>{
|
||||
|
||||
});
|
||||
}
|
||||
else{
|
||||
this.chatService.deleteChannel(body).subscribe(res=>{
|
||||
|
||||
});
|
||||
}
|
||||
});
|
||||
// if(this.room.t === 'p'){
|
||||
// this.chatService.deleteGroup(body).subscribe(res=>{
|
||||
|
||||
// });
|
||||
// }
|
||||
// else{
|
||||
// this.chatService.deleteChannel(body).subscribe(res=>{
|
||||
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
}
|
||||
|
||||
|
||||
return this.countDownTime;
|
||||
}
|
||||
|
||||
@@ -97,7 +98,7 @@ export class TimeService {
|
||||
// });
|
||||
// }
|
||||
// else{
|
||||
|
||||
|
||||
// this.chatService.deleteChannel(body).subscribe(res=>{
|
||||
// this.ChatSystemService.deleteRoom(roomId)
|
||||
// });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { ToastService } from 'src/app/services/toast.service';
|
||||
import { BackgroundService } from 'src/app/services/background.service';
|
||||
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
@@ -12,7 +12,7 @@ export class HttpErrorHandle {
|
||||
private backgroundService: BackgroundService
|
||||
) { }
|
||||
|
||||
async httpStatusHandle(error) {
|
||||
async httpStatusHandle(error: any) {
|
||||
switch (error.status
|
||||
) {
|
||||
case 0:
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { HttpServiceService } from './http-service.service';
|
||||
|
||||
describe('HttpServiceService', () => {
|
||||
let service: HttpServiceService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(HttpServiceService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
// import { DateTime } from 'luxon';
|
||||
|
||||
// type GetDateWithFormatFormatInput = {
|
||||
// date?: Date;
|
||||
// format?: string;
|
||||
// };
|
||||
|
||||
// export class DateUtils {
|
||||
// static getDateStringWithFormat(
|
||||
// input: Partial<GetDateWithFormatFormatInput> = {},
|
||||
// ): string {
|
||||
// if (!input?.date) {
|
||||
// Object.assign(input, { date: DateUtils.getJSDate() });
|
||||
// }
|
||||
|
||||
// if (!input?.format) {
|
||||
// Object.assign(input, { format: process.env.DATE_FORMAT });
|
||||
// }
|
||||
|
||||
// return DateTime.fromJSDate(input.date, { zone: 'utc' })
|
||||
// .setZone(process.env.TZ)
|
||||
// .toFormat(input.format);
|
||||
// }
|
||||
|
||||
// static getISODateString(): string {
|
||||
// return DateTime.fromJSDate(DateUtils.getJSDate(), { zone: 'utc' })
|
||||
// .setZone(process.env.TZ)
|
||||
// .toJSON();
|
||||
// }
|
||||
|
||||
// static getISODateJSDateObject(dateObject: Date): string {
|
||||
// // Convert the JavaScript Date object to Luxon DateTime
|
||||
// const luxonDateTime = DateTime.fromJSDate(dateObject, { zone: 'utc' });
|
||||
|
||||
// // Get the ISO 8601 formatted string in UTC
|
||||
// const isoDateString = luxonDateTime.toISO();
|
||||
|
||||
// return isoDateString;
|
||||
// }
|
||||
|
||||
|
||||
// static getJSDate(): Date {
|
||||
// return DateTime.fromJSDate(DateTime.now().toJSDate(), { zone: 'utc' })
|
||||
// .setZone(process.env.TZ)
|
||||
// .toJSDate();
|
||||
// }
|
||||
|
||||
// static getDate(): DateTime {
|
||||
// return DateTime.fromJSDate(DateUtils.getJSDate(), { zone: 'utc' }).setZone(
|
||||
// process.env.TZ,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
@@ -1,64 +1,66 @@
|
||||
|
||||
export type MessageType = {
|
||||
message: string;
|
||||
context?: string;
|
||||
obj?: object;
|
||||
};
|
||||
|
||||
function getCurrentTime() {
|
||||
const now = new Date();
|
||||
const hours = String(now.getHours()).padStart(2, '0');
|
||||
const minutes = String(now.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(now.getSeconds()).padStart(2, '0');
|
||||
const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
|
||||
return `${hours}:${minutes}:${seconds}.${milliseconds}`;
|
||||
}
|
||||
|
||||
// function getCurrentTime() {
|
||||
// const now = new Date();
|
||||
// const hours = String(now.getHours()).padStart(2, '0');
|
||||
// const minutes = String(now.getMinutes()).padStart(2, '0');
|
||||
// const seconds = String(now.getSeconds()).padStart(2, '0');
|
||||
// const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
|
||||
// return `${hours}:${minutes}:${seconds}.${milliseconds}`;
|
||||
// }
|
||||
export class ColoredLoggerService {
|
||||
|
||||
constructor() {}
|
||||
|
||||
// export class Logger {
|
||||
// private app!: string;
|
||||
static log(message: string): void {
|
||||
console.log(
|
||||
`[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
'color: #00897B', // CSS Style
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
// constructor() {}
|
||||
static debug({ message, context, obj = {} }: MessageType): void {
|
||||
console.info(
|
||||
`[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
'color: #039BE5', // CSS Style
|
||||
Object.assign(obj, { context, createdAt: getCurrentTime(), message })
|
||||
);
|
||||
}
|
||||
|
||||
// static log(message: string): void {
|
||||
// console.log(
|
||||
// `[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
// 'color: #00897B', // CSS Style
|
||||
// message
|
||||
// );
|
||||
// }
|
||||
static info({ message, context, obj = {} }: MessageType): void {
|
||||
console.info(
|
||||
`[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
'color: #039BE5', // CSS Style
|
||||
Object.assign(obj, { context, createdAt: getCurrentTime(), message })
|
||||
);
|
||||
}
|
||||
|
||||
// static debug({ message, context, obj = {} }: MessageType): void {
|
||||
// console.info(
|
||||
// `[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
// 'color: #039BE5', // CSS Style
|
||||
// Object.assign(obj, { context, createdAt: DateUtils.getISODateString(), message })
|
||||
// );
|
||||
// }
|
||||
static warn({ message, context, obj = {} }: MessageType): void {
|
||||
console.warn(
|
||||
`[${getCurrentTime()}] %cWARN : `, // Console Message
|
||||
'color: #FB8C00', // CSS Style
|
||||
Object.assign(obj, { context, createdAt: getCurrentTime(), message })
|
||||
);
|
||||
}
|
||||
|
||||
// static info({ message, context, obj = {} }: MessageType): void {
|
||||
// console.info(
|
||||
// `[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
// 'color: #039BE5', // CSS Style
|
||||
// Object.assign(obj, { context, createdAt: DateUtils.getISODateString(), message })
|
||||
// );
|
||||
// }
|
||||
static error(error: any = "", message?: string, context = ""): void {
|
||||
|
||||
// static warn({ message, context, obj = {} }: MessageType): void {
|
||||
// console.warn(
|
||||
// `[${getCurrentTime()}] %cWARN : `, // Console Message
|
||||
// 'color: #FB8C00', // CSS Style
|
||||
// Object.assign(obj, { context, createdAt: DateUtils.getISODateString(), message })
|
||||
// );
|
||||
// }
|
||||
console.error(
|
||||
`[${getCurrentTime()}] %cERROR : `, // Console Message
|
||||
'color: #E53935', // CSS Style
|
||||
message+', '+ context,
|
||||
'\n',
|
||||
error,
|
||||
'\n',
|
||||
);
|
||||
}
|
||||
|
||||
// static error(error: any = "", message?: string, context = ""): void {
|
||||
|
||||
// console.error(
|
||||
// `[${getCurrentTime()}] %cERROR : `, // Console Message
|
||||
// 'color: #E53935', // CSS Style
|
||||
// message+', '+ context,
|
||||
// '\n',
|
||||
// error,
|
||||
// '\n',
|
||||
// );
|
||||
// }
|
||||
|
||||
// fatal(error?: ErrorType, message?: string, context?: string): void {}
|
||||
// }
|
||||
fatal(error?: any, message?: string, context?: string): void {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// import { DateUtils } from './date';
|
||||
|
||||
import { environment } from "src/environments/environment";
|
||||
import { openTelemetryLogging } from "../../monitoring/opentelemetry/logging";
|
||||
import { SessionStore } from "src/app/store/session.service";
|
||||
import { DeviceInfo } from "@capacitor/device";
|
||||
import { Device } from '@capacitor/device';
|
||||
|
||||
export type MessageType = {
|
||||
message: string;
|
||||
context?: string;
|
||||
obj?: object;
|
||||
};
|
||||
|
||||
function getCurrentTime() {
|
||||
const now = new Date();
|
||||
const hours = String(now.getHours()).padStart(2, '0');
|
||||
const minutes = String(now.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(now.getSeconds()).padStart(2, '0');
|
||||
const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
|
||||
return `${hours}:${minutes}:${seconds}.${milliseconds}`;
|
||||
}
|
||||
|
||||
let device: DeviceInfo;
|
||||
|
||||
Device.getInfo().then(e => {
|
||||
device = e
|
||||
});
|
||||
|
||||
export class Logger {
|
||||
|
||||
constructor() {}
|
||||
|
||||
static log(message: string, obj = {}): void {
|
||||
console.log(
|
||||
`[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
'color: #00897B', // CSS Style
|
||||
Object.assign(obj, { createdAt: getCurrentTime(), message })
|
||||
);
|
||||
|
||||
|
||||
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
|
||||
openTelemetryLogging.send({
|
||||
type: 'graylog',
|
||||
spanContext: null,
|
||||
payload: {
|
||||
message: message,
|
||||
object: {
|
||||
...obj,
|
||||
spanId: null,
|
||||
name,
|
||||
user: SessionStore?.user?.FullName,
|
||||
device_name: device?.name || device?.model,
|
||||
commit_date: environment.version.lastCommitTime,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static debug(message: string, obj = {}): void {
|
||||
console.info(
|
||||
`[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
'color: #039BE5', // CSS Style
|
||||
Object.assign(obj, {createdAt: getCurrentTime(), message })
|
||||
);
|
||||
|
||||
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
|
||||
openTelemetryLogging.send({
|
||||
type: 'graylog',
|
||||
spanContext: null,
|
||||
payload: {
|
||||
message: message,
|
||||
object: {
|
||||
...obj,
|
||||
spanId: null,
|
||||
name,
|
||||
user: SessionStore?.user?.FullName,
|
||||
device_name: device?.name || device?.model,
|
||||
commit_date: environment.version.lastCommitTime,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static info(message: string, obj = {}): void {
|
||||
console.info(
|
||||
`[${getCurrentTime()}] %cINFO : `, // Console Message
|
||||
'color: #039BE5', // CSS Style
|
||||
message+' '+
|
||||
'\n',
|
||||
obj,
|
||||
'\n',
|
||||
);
|
||||
|
||||
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
|
||||
openTelemetryLogging.send({
|
||||
type: 'graylog',
|
||||
spanContext: null,
|
||||
payload: {
|
||||
message: message,
|
||||
object: {
|
||||
...obj,
|
||||
spanId: null,
|
||||
name,
|
||||
user: SessionStore?.user?.FullName,
|
||||
device_name: device?.name || device?.model,
|
||||
commit_date: environment.version.lastCommitTime,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static warn(message: string, obj = {}): void {
|
||||
console.warn(
|
||||
`[${getCurrentTime()}] %cWARN : `, // Console Message
|
||||
'color: #FB8C00', // CSS Style
|
||||
message+' '+
|
||||
'\n',
|
||||
obj,
|
||||
'\n',
|
||||
);
|
||||
|
||||
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
|
||||
openTelemetryLogging.send({
|
||||
type: 'graylog',
|
||||
spanContext: null,
|
||||
payload: {
|
||||
message: message,
|
||||
object: {
|
||||
...obj,
|
||||
spanId: null,
|
||||
name,
|
||||
user: SessionStore?.user?.FullName,
|
||||
device_name: device?.name || device?.model,
|
||||
commit_date: environment.version.lastCommitTime,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static error(message?: string, obj = {}): void {
|
||||
|
||||
console.error(
|
||||
`[${getCurrentTime()}] %cERROR : `, // Console Message
|
||||
'color: #E53935', // CSS Style
|
||||
message+' '+
|
||||
'\n',
|
||||
obj,
|
||||
'\n',
|
||||
);
|
||||
|
||||
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
|
||||
openTelemetryLogging.send({
|
||||
type: 'graylog',
|
||||
spanContext: null,
|
||||
payload: {
|
||||
message: message,
|
||||
object: {
|
||||
...obj,
|
||||
spanId: null,
|
||||
name,
|
||||
user: SessionStore?.user?.FullName,
|
||||
device_name: device?.name || device?.model,
|
||||
commit_date: environment.version.lastCommitTime,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fatal(error?: any, message?: string, context?: string): void {}
|
||||
}
|
||||
@@ -12,18 +12,18 @@ export class OpenTelemetryLogging {
|
||||
constructor() {
|
||||
|
||||
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
|
||||
this.socket.start()
|
||||
// this.socket.start()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
send(data: Object & { type: string; payload: any, spanContext:any }): void {
|
||||
this.socket.send({
|
||||
type: data.type,
|
||||
payload: data.payload,
|
||||
requestId: uuidv4(),
|
||||
spanContext: data.spanContext
|
||||
});
|
||||
// this.socket.send({
|
||||
// type: data.type,
|
||||
// payload: data.payload,
|
||||
// requestId: uuidv4(),
|
||||
// spanContext: data.spanContext
|
||||
// });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { metrics } from '@opentelemetry/api';
|
||||
import { Histogram, metrics } from '@opentelemetry/api';
|
||||
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
|
||||
import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
|
||||
import { Subject } from 'rxjs';
|
||||
@@ -10,34 +10,22 @@ const meterProvider = new MeterProvider();
|
||||
metrics.setGlobalMeterProvider(meterProvider);
|
||||
|
||||
if (window.location.protocol !== 'https:' && environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
|
||||
const metricReader = new PeriodicExportingMetricReader({
|
||||
exporter: new OTLPMetricExporter({
|
||||
//url: 'https://5-180-182-151.cloud-xip.com:85/collector2/v1/metrics',
|
||||
url: 'https://185-229-224-75.cloud-xip.com:85/collector2/v1/metrics',
|
||||
//url: 'http://5-180-182-151.cloud-xip.com:4318/v1/metrics',
|
||||
//url: 'http://185-229-224-75.cloud-xip.com:4318/v1/metrics'
|
||||
// headers: {
|
||||
// 'Authorization': 'Basic ' + btoa('tabteste@006:tabteste@006'),
|
||||
// }
|
||||
}),
|
||||
exportIntervalMillis: 30000,
|
||||
});
|
||||
|
||||
meterProvider.addMetricReader(metricReader);
|
||||
|
||||
const subject = new Subject()
|
||||
|
||||
subject
|
||||
.pipe(
|
||||
throttleTime(5000) // 5000 milliseconds = 5 seconds
|
||||
)
|
||||
.subscribe(() => {
|
||||
metricReader.forceFlush().then(() => {
|
||||
console.log('Metrics exported');
|
||||
});
|
||||
});
|
||||
// const metricReader = new PeriodicExportingMetricReader({
|
||||
// exporter: new OTLPMetricExporter({
|
||||
// //url: 'https://5-180-182-151.cloud-xip.com:85/collector2/v1/metrics',
|
||||
// url: 'https://185-229-224-75.cloud-xip.com:85/collector2/v1/metrics',
|
||||
// //url: 'http://5-180-182-151.cloud-xip.com:4318/v1/metrics',
|
||||
// //url: 'http://185-229-224-75.cloud-xip.com:4318/v1/metrics'
|
||||
// // headers: {
|
||||
// // 'Authorization': 'Basic ' + btoa('tabteste@006:tabteste@006'),
|
||||
// // }
|
||||
// }),
|
||||
// exportIntervalMillis: 30000,
|
||||
// });
|
||||
|
||||
// meterProvider.addMetricReader(metricReader);
|
||||
}
|
||||
|
||||
export const meter = meterProvider.getMeter('example-exporter-collector');
|
||||
export const RequestCounter = meter.createCounter('post_requests', {
|
||||
description: 'Example of a Counter',
|
||||
@@ -46,3 +34,10 @@ export const RequestCounter = meter.createCounter('post_requests', {
|
||||
export const UseCaseCounter = meter.createCounter('use_case', {
|
||||
description: 'use case counter',
|
||||
});
|
||||
|
||||
|
||||
// Assuming `meter` is your initialized Meter instance
|
||||
export const useCaseDurationHistogram: Histogram = meter.createHistogram('use_case_duration', {
|
||||
description: 'Duration of use cases',
|
||||
unit: 'milliseconds',
|
||||
});
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
|
||||
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
|
||||
import { ZipkinExporter } from '@opentelemetry/exporter-zipkin';
|
||||
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
|
||||
import { Resource } from '@opentelemetry/resources';
|
||||
//import { OTLPTraceExporter } from '@opentelemetry/exporter-otlp-http';
|
||||
import { context, trace, propagation } from '@opentelemetry/api';
|
||||
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
|
||||
// const { OTLPTraceExporter: OTLPTraceExporterProto } = require("@opentelemetry/exporter-trace-otlp-proto");
|
||||
|
||||
|
||||
function createProvider(serviceName) {
|
||||
const provider = new WebTracerProvider({
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
|
||||
import { Tracer, Span } from '@opentelemetry/sdk-trace-base';
|
||||
import { OpentelemetryAgendaProvider, OpentelemetryInterceptorProvider, OpentelemetryLogging, OpentelemetryNotificationProvider } from './opentelemetry';
|
||||
import { OpentelemetryAgendaProvider, OpentelemetryChatProvider, OpentelemetryInterceptorProvider, OpentelemetryLogging, OpentelemetryNotificationProvider } from './opentelemetry';
|
||||
import { Device, DeviceInfo } from '@capacitor/device';
|
||||
import { SessionStore } from 'src/app/store/session.service';
|
||||
import { environment } from 'src/environments/environment';
|
||||
import { UseCaseCounter } from './matrix';
|
||||
import { UseCaseCounter, useCaseDurationHistogram } from './matrix';
|
||||
import { openTelemetryLogging } from './logging';
|
||||
// import { context, propagation } from '@opentelemetry/api';
|
||||
import {
|
||||
SpanStatus, SpanStatusCode
|
||||
} from '@opentelemetry/api';
|
||||
import { Logger } from '../../logger/main/service';
|
||||
const tracerInstance = OpentelemetryAgendaProvider.getTracer('example-tracer-hole', '111', {})
|
||||
const tracerNotificationInstance = OpentelemetryNotificationProvider.getTracer('example-tracer-hole', '111', {})
|
||||
// const logger: ILoggerAdapter = new ColoredLoggerService()
|
||||
|
||||
const tracerChat = OpentelemetryChatProvider.getTracer('OpentelemetryChatProvider','some' ,{})
|
||||
let device: DeviceInfo;
|
||||
|
||||
Device.getInfo().then(e => {
|
||||
@@ -40,17 +39,22 @@ function convertAttributesToString(obj) {
|
||||
}
|
||||
|
||||
|
||||
const createTracingInstance = ({bugPrint, name, module, autoFinish}): TracingType => {
|
||||
const requestId = uuidv4()
|
||||
const createTracingInstance = ({bugPrint, name, module, autoFinish, waitNThrow = 0}): TracingType => {
|
||||
|
||||
const startTime = Date.now();
|
||||
const requestId = uuidv4()
|
||||
let _tracerInstance:Tracer
|
||||
|
||||
if(module == 'notification') {
|
||||
_tracerInstance = tracerNotificationInstance
|
||||
} else if (module == 'chat') {
|
||||
_tracerInstance = tracerChat
|
||||
} else {
|
||||
_tracerInstance = tracerInstance
|
||||
}
|
||||
|
||||
let waitNThrowFunction: NodeJS.Timeout | undefined
|
||||
|
||||
const span = _tracerInstance.startSpan(name);
|
||||
let finish = false
|
||||
|
||||
@@ -58,10 +62,12 @@ const createTracingInstance = ({bugPrint, name, module, autoFinish}): TracingTyp
|
||||
event: {},
|
||||
tags: {},
|
||||
status: {} as any,
|
||||
logs:[]
|
||||
logs:[],
|
||||
errors: []
|
||||
}
|
||||
|
||||
const returnObject = {
|
||||
name,
|
||||
span: span as any,
|
||||
tracer: tracerInstance,
|
||||
tracerId: requestId,
|
||||
@@ -69,12 +75,10 @@ const createTracingInstance = ({bugPrint, name, module, autoFinish}): TracingTyp
|
||||
setStatus: (status: SpanStatus) => {
|
||||
span.setStatus(status);
|
||||
},
|
||||
addEvent: (context: string, message?: any, obj?: any) => {
|
||||
addEvent: (context: string, message: string = "") => {
|
||||
|
||||
data.event[context] = message;
|
||||
|
||||
const value = [JSON.stringify(message)] as any
|
||||
span.addEvent(context, value);
|
||||
span.addEvent(context, message as any);
|
||||
},
|
||||
LocalLogEvent:(context: string, message: any, obj: any) => {
|
||||
data.tags[context] = message;
|
||||
@@ -84,7 +88,9 @@ const createTracingInstance = ({bugPrint, name, module, autoFinish}): TracingTyp
|
||||
span.setAttribute(key, value);
|
||||
|
||||
if(key =='outcome' && value == 'failed') {
|
||||
returnObject.hasError('error')
|
||||
if(data.errors.length == 0) {
|
||||
returnObject.hasError('error')
|
||||
}
|
||||
if(!autoFinish) {
|
||||
returnObject.finish()
|
||||
}
|
||||
@@ -129,8 +135,13 @@ const createTracingInstance = ({bugPrint, name, module, autoFinish}): TracingTyp
|
||||
finish: () => {
|
||||
if(finish) return
|
||||
|
||||
if(waitNThrowFunction) {
|
||||
clearTimeout(waitNThrowFunction);
|
||||
}
|
||||
|
||||
if(environment.apiURL != 'https://gdqas-api.oapr.gov.ao/api/') {
|
||||
span.end();
|
||||
span.setAttribute('error.list', data.errors.join(','))
|
||||
// span.end();
|
||||
UseCaseCounter.add(1, {user: SessionStore?.user?.FullName, outcome:data.tags['outcome'] || data.status?.code , usecase: name})
|
||||
}
|
||||
|
||||
@@ -138,23 +149,36 @@ const createTracingInstance = ({bugPrint, name, module, autoFinish}): TracingTyp
|
||||
console.error(name, data)
|
||||
}
|
||||
|
||||
const duration = Date.now() - (startTime as unknown as number);
|
||||
useCaseDurationHistogram.record(duration, { use_case: name });
|
||||
useCaseDurationHistogram.record(duration, { use_case: name, user: SessionStore.user.UserName });
|
||||
|
||||
finish = true
|
||||
},
|
||||
hasError:(message: string) => {
|
||||
if(data.status?.code != SpanStatusCode.ERROR) {
|
||||
data.status = {code: SpanStatusCode.ERROR, message}
|
||||
span.setStatus({code: SpanStatusCode.ERROR, message})
|
||||
span.setAttribute('outcome','failed')
|
||||
}
|
||||
hasError:(message: string, obj:Object = {}) => {
|
||||
const spanId = span.spanContext().spanId;
|
||||
|
||||
data.errors.push(message)
|
||||
data.status = {code: SpanStatusCode.ERROR, message}
|
||||
span.setStatus({code: SpanStatusCode.ERROR, message})
|
||||
Logger.error(message, {...obj, spanId, name})
|
||||
},
|
||||
createSpan: (name, parent?: any) => {
|
||||
return tracerInstance.startSpan(name, { root: false }, parent) as Span;
|
||||
}
|
||||
}
|
||||
|
||||
if(waitNThrow > 0) {
|
||||
waitNThrowFunction = setTimeout(()=> {
|
||||
returnObject.hasError('waitNThrowFunction')
|
||||
returnObject.finish()
|
||||
}, waitNThrow)
|
||||
}
|
||||
|
||||
return returnObject
|
||||
}
|
||||
|
||||
export function XTracerAsync({ name, bugPrint, module = null, autoFinish = true, daley =0 }) {
|
||||
export function XTracerAsync({ name, bugPrint, module = null, autoFinish = true, daley =0, waitNThrow = 0 }) {
|
||||
return (
|
||||
target: unknown,
|
||||
propertyKey: string,
|
||||
@@ -164,7 +188,8 @@ export function XTracerAsync({ name, bugPrint, module = null, autoFinish = true,
|
||||
descriptor.value = async function (...args: unknown[]) {
|
||||
|
||||
|
||||
const tracing = createTracingInstance({bugPrint, name, module, autoFinish})
|
||||
|
||||
const tracing = createTracingInstance({bugPrint, name, module, autoFinish, waitNThrow})
|
||||
|
||||
tracing.setAttribute('User', SessionStore?.user?.FullName);
|
||||
tracing.setAttribute('current.page', window.location.pathname);
|
||||
@@ -185,6 +210,9 @@ export function XTracerAsync({ name, bugPrint, module = null, autoFinish = true,
|
||||
return result
|
||||
} catch (e) {
|
||||
tracing.setAttribute('catch', 'true')
|
||||
tracing.log("cath", {
|
||||
error: e
|
||||
})
|
||||
|
||||
if(autoFinish) {
|
||||
setTimeout(tracing.finish , daley)
|
||||
@@ -197,7 +225,7 @@ export function XTracerAsync({ name, bugPrint, module = null, autoFinish = true,
|
||||
}
|
||||
|
||||
|
||||
export function XTracer({ name, bugPrint, module, autoFinish = true, daley =0 }) {
|
||||
export function XTracer({ name, bugPrint, module, autoFinish = true, daley =0, waitNThrow =0 }) {
|
||||
return (
|
||||
target: unknown,
|
||||
propertyKey: string,
|
||||
@@ -206,7 +234,7 @@ export function XTracer({ name, bugPrint, module, autoFinish = true, daley =0 })
|
||||
const originalMethod = descriptor.value;
|
||||
descriptor.value = function (...args: unknown[]) {
|
||||
|
||||
const tracing = createTracingInstance({bugPrint, name, module, autoFinish})
|
||||
const tracing = createTracingInstance({bugPrint, name, module, autoFinish, waitNThrow})
|
||||
|
||||
tracing.setAttribute('User', SessionStore?.user?.FullName);
|
||||
tracing.setAttribute('current.page', window.location.pathname);
|
||||
@@ -227,6 +255,9 @@ export function XTracer({ name, bugPrint, module, autoFinish = true, daley =0 })
|
||||
} catch (e) {
|
||||
|
||||
tracing.setAttribute('catch', 'true')
|
||||
tracing.log("cath", {
|
||||
error: e
|
||||
})
|
||||
|
||||
if(autoFinish) {
|
||||
setTimeout(tracing.finish , daley)
|
||||
@@ -239,6 +270,7 @@ export function XTracer({ name, bugPrint, module, autoFinish = true, daley =0 })
|
||||
}
|
||||
|
||||
export type TracingType = {
|
||||
name: string,
|
||||
span: Span;
|
||||
tracer: Tracer;
|
||||
tracerId: string;
|
||||
@@ -251,7 +283,7 @@ export type TracingType = {
|
||||
getAttribute: (key: string) => string;
|
||||
LocalLogEvent: (name: string, attributesOrStartTime: any, obj?:any) => void;
|
||||
finish: () => void;
|
||||
hasError:(message: string) => void;
|
||||
hasError:(message: string, obj?: Object) => void;
|
||||
createSpan:(name, parent?: any) => Span;
|
||||
};
|
||||
|
||||
|
||||
@@ -13,26 +13,26 @@ export class WebSocketGraylogService {
|
||||
|
||||
connect(): void {
|
||||
// this.adminSocketGlobal = new WebSocket('wss://5-180-182-151.cloud-xip.com:85/ws/');
|
||||
this.adminSocketGlobal = new WebSocket('wss://185-229-224-75.cloud-xip.com:85/ws/');
|
||||
// this.adminSocketGlobal = new WebSocket('wss://185-229-224-75.cloud-xip.com:85/ws/');
|
||||
|
||||
this.adminSocketGlobal.onopen = () => {
|
||||
console.log('Admin WebSocket is open now.');
|
||||
this.adminSocketGlobal.send("uuid");
|
||||
this.connected = true
|
||||
};
|
||||
// this.adminSocketGlobal.onopen = () => {
|
||||
// console.log('Admin WebSocket is open now.');
|
||||
// this.adminSocketGlobal.send("uuid");
|
||||
// this.connected = true
|
||||
// };
|
||||
|
||||
this.adminSocketGlobal.onmessage = async (event: MessageEvent) => {
|
||||
// Handle incoming messages here
|
||||
};
|
||||
// this.adminSocketGlobal.onmessage = async (event: MessageEvent) => {
|
||||
// // Handle incoming messages here
|
||||
// };
|
||||
|
||||
this.adminSocketGlobal.onclose = () => {
|
||||
console.log('Admin WebSocket is closed now.');
|
||||
this.connect();
|
||||
};
|
||||
// this.adminSocketGlobal.onclose = () => {
|
||||
// // console.log('Admin WebSocket is closed now.');
|
||||
// this.connect();
|
||||
// };
|
||||
|
||||
this.adminSocketGlobal.onerror = (error: Event) => {
|
||||
console.error('Admin WebSocket error:', error);
|
||||
};
|
||||
// this.adminSocketGlobal.onerror = (error: Event) => {
|
||||
// // console.error('Admin WebSocket error:', error);
|
||||
// };
|
||||
}
|
||||
|
||||
send(data: Object & { type: string; payload: Object , requestId: string, spanContext:any }): void {
|
||||
@@ -43,14 +43,12 @@ export class WebSocketGraylogService {
|
||||
payload: data.payload,
|
||||
requestId: data.requestId,
|
||||
parentSpan: {
|
||||
traceId: data.spanContext.spanContext().traceId,
|
||||
spanId: data.spanContext.spanContext().spanId,
|
||||
traceId: data?.spanContext?.spanContext().traceId,
|
||||
spanId: data?.spanContext?.spanContext().spanId,
|
||||
}
|
||||
}));
|
||||
|
||||
// data.spanContext.end()
|
||||
} else {
|
||||
console.warn('WebSocket is not open. Message not sent.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ import { Capacitor } from '@capacitor/core';
|
||||
import { AngularFireMessaging } from '@angular/fire/messaging';
|
||||
import { NotificationHolderService } from 'src/app/store/notification-holder.service';
|
||||
import { FCM } from '@capacitor-community/fcm';
|
||||
import {ChatController} from 'src/app/controller/chat'
|
||||
import { TracingType, XTracer, XTracerAsync } from 'src/app/services/monitoring/opentelemetry/tracer';
|
||||
import { z } from 'zod';
|
||||
import { NotificationRepositoryService } from 'src/app/module/notification/data/notification-repository.service'
|
||||
@@ -32,6 +31,9 @@ const notificationSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
// import { ChatSystemService } from './chat/chat-system.service';
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
@@ -56,8 +58,6 @@ export class NotificationsService {
|
||||
notificationReceived: EventEmitter<void> = new EventEmitter<void>();
|
||||
token = ''
|
||||
|
||||
ChatController = ChatController
|
||||
|
||||
constructor(
|
||||
private http: HttpClient,
|
||||
public modalCtrl: AlertController,
|
||||
|
||||
@@ -10,7 +10,6 @@ import { GetTasksListType } from '../models/GetTasksListType';
|
||||
import { fullTaskList } from '../models/dailyworktask.model';
|
||||
import { ChangeProfileService } from './change-profile.service';
|
||||
import { SessionStore } from '../store/session.service';
|
||||
import { CPSession } from '../store/documentManagement';
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { WebNotificationsService } from './webnotifications.service';
|
||||
|
||||
describe('WebNotificationsService', () => {
|
||||
let service: WebNotificationsService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(WebNotificationsService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,213 +0,0 @@
|
||||
import { Injectable, NgZone } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
|
||||
import { environment } from 'src/environments/environment';
|
||||
import { StorageService } from 'src/app/services/storage.service';
|
||||
import { AuthConnstants } from 'src/app/config/auth-constants';
|
||||
import { Tokenn } from '../models/token.model';
|
||||
import { ModalController, AlertController, AnimationController, Platform } from '@ionic/angular';
|
||||
import { NavigationExtras, Router } from '@angular/router';
|
||||
import { ToastService } from './toast.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class WebNotificationsService {
|
||||
|
||||
adding: "intervenient" | "CC" = "intervenient";
|
||||
folderId: string;
|
||||
|
||||
constructor(
|
||||
private http: HttpClient,
|
||||
private storageService: StorageService,
|
||||
private modalController: ModalController,
|
||||
public modalCtrl: AlertController,
|
||||
private animationController: AnimationController,
|
||||
private platform: Platform,
|
||||
private router: Router,
|
||||
private toastService: ToastService) { }
|
||||
|
||||
|
||||
webconnection() {
|
||||
|
||||
var inicializeObj = {
|
||||
appId: "com.gpr.gabinetedigital",
|
||||
mfpContextRoot: "/mfp",
|
||||
/* serverUrl: "http://gpr-dev-10.gabinetedigital.local:9080",
|
||||
safariWebsitePushId: "http://gpr-dev-10.gabinetedigital.local:9080", */
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* MFPPush.initialize({
|
||||
appId: "com.gpr.gabinetedigital",
|
||||
mfpContextRoot: "/mfp",
|
||||
}); */
|
||||
|
||||
/* MFPPush.registerDevice()
|
||||
.then((res) => {
|
||||
|
||||
|
||||
setTimeout(()=>{
|
||||
MFPPush.registerDevice()
|
||||
.then((res) => {
|
||||
|
||||
})
|
||||
.catch((err) => {
|
||||
|
||||
});
|
||||
}, 1000)
|
||||
|
||||
|
||||
})
|
||||
.catch((err) => {
|
||||
|
||||
}); */
|
||||
}
|
||||
|
||||
/* getTokenByUserIdAndId(user, userID) {
|
||||
const geturl = environment.apiURL + 'notifications/user/' + userID;
|
||||
|
||||
return this.http.get<Token[]>(`${geturl}`);
|
||||
} */
|
||||
|
||||
/* getAndpostToken(username) {
|
||||
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
|
||||
|
||||
} else {
|
||||
|
||||
const geturl = environment.apiURL + 'notifications/token'; */
|
||||
/*
|
||||
window['WLAuthorizationManager'].obtainAccessToken("push.mobileclient").then(
|
||||
(token) => {
|
||||
|
||||
|
||||
MFPPush.initialize(
|
||||
function (successResponse) {
|
||||
|
||||
},
|
||||
function (failureResponse) {
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
MFPPush.registerDevice(null, (successResponse) => {
|
||||
|
||||
|
||||
this.storageService.store(username, successResponse.deviceId);
|
||||
this.storageService.get(username).then(value => {
|
||||
|
||||
this.storageService.get(AuthConnstants.USER).then(res => {
|
||||
|
||||
const headers = { 'Authorization': 'Basic cGF1bG8ucGludG9AZ2FiaW5ldGVkaWdpdGFsLmxvY2FsOnRhYnRlc3RlQDAwNg==' };
|
||||
const body = {
|
||||
UserId: res.UserId,
|
||||
TokenId: successResponse.deviceId,
|
||||
Status: 1,
|
||||
Service: 1
|
||||
};
|
||||
this.http.post<Token>(`${geturl}`, body, { headers }).subscribe(data => {
|
||||
|
||||
})
|
||||
});
|
||||
|
||||
});
|
||||
},
|
||||
function (failureResponse) {
|
||||
|
||||
}
|
||||
);
|
||||
}, (error) => {
|
||||
|
||||
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
} */
|
||||
/*
|
||||
async onReceviNotification() {
|
||||
window['WLAuthorizationManager'].obtainAccessToken("push.mobileclient").then(
|
||||
(token) => {
|
||||
|
||||
|
||||
MFPPush.initialize(
|
||||
function (successResponse) {
|
||||
|
||||
MFPPush.registerNotificationsCallback(notificationReceived);
|
||||
},
|
||||
function (failureResponse) {
|
||||
|
||||
}
|
||||
);
|
||||
var notificationReceived = (message) => {
|
||||
|
||||
var data = JSON.parse(message.payload);
|
||||
|
||||
|
||||
|
||||
|
||||
if(message.actionName){
|
||||
this.notificatinsRoutes(data);
|
||||
} else {
|
||||
this.toastService.notificationMessage(message.alert,this.notificatinsRoutes, data);
|
||||
}
|
||||
|
||||
}
|
||||
}, (error) => {
|
||||
|
||||
|
||||
}
|
||||
);
|
||||
} */
|
||||
|
||||
/* notificatinsRoutes = (data) => {
|
||||
if (data.Service === "agenda") {
|
||||
this.zone.run(() => this.router.navigate(['/home/agenda', data.IdObject, 'agenda']));
|
||||
}
|
||||
else if (data.Service === "gabinete-digital" && data.Object === "expediente") {
|
||||
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expediente',data.IdObject,'gabinete-digital']));
|
||||
}
|
||||
else if (data.Service === "gabinete-digital" && data.Object === "event-list") {
|
||||
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/event-list/approve-event',data.IdObject, 'gabinete-digital']));
|
||||
}else if (data.Service === "gabinete-digital" && data.Object === "despachos") {
|
||||
let navigationExtras: NavigationExtras = {
|
||||
queryParams: {
|
||||
"serialNumber": data.IdObject,
|
||||
}
|
||||
};
|
||||
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos/despacho'], navigationExtras));
|
||||
}
|
||||
else if (data.Service === "gabinete-digital" && data.Object === "parecer") {
|
||||
let navigationExtras: NavigationExtras = {
|
||||
queryParams: {
|
||||
enterAnimation: "",
|
||||
serialNumber: data.IdObject,
|
||||
}
|
||||
};
|
||||
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos/pedido'], navigationExtras));
|
||||
}
|
||||
else if (data.Service === "gabinete-digital" && data.Object === "deferimento") {
|
||||
let navigationExtras: NavigationExtras = {
|
||||
queryParams: {
|
||||
enterAnimation: "",
|
||||
serialNumber: data.IdObject,
|
||||
}
|
||||
};
|
||||
this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos/pedido'], navigationExtras));
|
||||
}
|
||||
else if (data.Service === "accoes" && data.Object === "accao") {
|
||||
this.zone.run(() => this.router.navigate(['/home/publications',data.IdObject]));
|
||||
}
|
||||
else if (data.Service === "accoes" && data.Object === "publicacao") {
|
||||
this.zone.run(() => this.router.navigate(['/home/publications/view-publications',data.FolderId,data.IdObject]));
|
||||
}
|
||||
}
|
||||
|
||||
platformVerify() {
|
||||
|
||||
if (this.platform.is('cordova')) {
|
||||
} else {
|
||||
}
|
||||
} */
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { z, ZodSchema, ZodError } from "zod";
|
||||
|
||||
// Utility function to attach metadata
|
||||
export function attachMetadata<T extends ZodSchema<any>>(schema: T, metadata: Record<string, any>): T {
|
||||
return (schema.refine(value => true, { message: "Metadata attached", ...metadata }) as any) as T;
|
||||
}
|
||||
|
||||
// Function to get metadata from a Zod error
|
||||
export function getMetadata<T extends ZodSchema<any>>(schema: T, error: ZodError): Record<string, any> | undefined {
|
||||
const metadataIssue = error.errors.find(issue => issue.message === "Metadata attached");
|
||||
return metadataIssue ? metadataIssue : undefined;
|
||||
}
|
||||
Reference in New Issue
Block a user