add error message

This commit is contained in:
Peter Maquiran
2024-06-11 11:46:04 +01:00
parent f3232c835d
commit fe51b38257
27 changed files with 675 additions and 478 deletions
-3
View File
@@ -4,7 +4,6 @@ import { Platform } from '@ionic/angular';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { NgxMatDateFormats } from '@angular-material-components/datetime-picker';
import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker';
import { ChatSystemService } from 'src/app/services/chat/chat-system.service';
import { InativityService } from "src/app/services/inativity.service";
import { ThemeService } from 'src/app/services/theme.service';
import { environment } from 'src/environments/environment';
@@ -41,7 +40,6 @@ export class AppComponent {
private statusBar: StatusBar,
public ThemeService: ThemeService,
private storage: Storage,
private ChatSystemService: ChatSystemService,
private sanitizer: DomSanitizer,
private screenOrientation: ScreenOrientation
) {
@@ -49,7 +47,6 @@ export class AppComponent {
window["sanitizer"] = this.sanitizer
this.initializeApp();
this.storage.set('version', environment.version).then(() => {})
ChatController.ChatSystemService = this.ChatSystemService
}
+27 -27
View File
@@ -1,5 +1,5 @@
import { chatUser } from '../models/chatMethod'
import { ChatController } from './chat'
//import { ChatController } from './chat'
export class EventController {
static create() {
@@ -12,36 +12,36 @@ export class EventController {
static async createOrFindGroupFromEvent(name, attendees) {
// chatController.
const {data, roomName} = await ChatController.createGroup(name)
// const {data, roomName} = await ChatController.createGroup(name)
const roomId = data.rid
// const roomId = data.rid
if (data.error.error == "error-duplicate-channel-name") {
const getGroupByName = ChatController.ChatSystemService.getGroupByName(roomName)
if(getGroupByName) {
return getGroupByName
}
} else if (roomId) {
const room = await ChatController.ChatSystemService.waitRoomToCreate(roomId)
const chatUsers: chatUser[] = []
// if (data.error.error == "error-duplicate-channel-name") {
// const getGroupByName = ChatController.ChatSystemService.getGroupByName(roomName)
// if(getGroupByName) {
// return getGroupByName
// }
// } else if (roomId) {
// const room = await ChatController.ChatSystemService.waitRoomToCreate(roomId)
for (let webTRIXUser of attendees ) {
const username = webTRIXUser.EmailAddress.split("@")[0];
const name = webTRIXUser.Name
const findChatUser = ChatController.ChatSystemService.searchContact(name, username)
if(findChatUser) {
chatUsers.push(findChatUser)
}
}
for (let chatUser of chatUsers) {
room.addContacts(chatUser._id)
}
// const chatUsers: chatUser[] = []
return room
}
// for (let webTRIXUser of attendees ) {
// const username = webTRIXUser.EmailAddress.split("@")[0];
// const name = webTRIXUser.Name
// const findChatUser = ChatController.ChatSystemService.searchContact(name, username)
// if(findChatUser) {
// chatUsers.push(findChatUser)
// }
// }
// for (let chatUser of chatUsers) {
// room.addContacts(chatUser._id)
// }
// return room
// }
}
+8 -15
View File
@@ -150,8 +150,16 @@
[roomId]="roomId"
(backToChat)="backToChat($event)"
(closeAllDesktopComponents)="closeAllDesktopComponents()"
(openGroupContacts)="openGroupContactsPage($event)"
(openEditGroupPage)="openEditGroupPage($event)"
(getGroups)="getGroups($event)"
*ngIf="showNewGroup"
class=" height-100 flex-column d-flex">
</app-new-group>
<app-edit-group [roomId]="roomId"
@@ -171,21 +179,6 @@
>
</app-group-contacts>
<app-new-event
*ngIf="showNewEvent"
[profile]=""
[roomId]="groupRoomId"
[selectedSegment]=segment
[taskParticipants]="taskParticipants"
[taskParticipantsCc]="taskParticipantsCc"
[selectedDate]="eventSelectedDate"
[eventAttendees]="contacts"
(onAddEvent)="closeNewEventComponentAndOpenChat($event)"
(openAttendeesComponent)="openAttendeesComponent($event)"
(backToChat)="backToChat($event)"
[style.display]="showNewEvent ? 'flex' : 'none'"
class=" height-100 flex-column">
</app-new-event>
<app-attendee-modal
[adding]="adding"
[taskParticipants]="taskParticipants"
+3 -5
View File
@@ -129,13 +129,9 @@ export class ChatPage implements OnInit {
public ThemeService: ThemeService,
private dataService: DataService,
private router: Router,
private sqlservice: SqliteService,
private platform: Platform,
private storageservice: StorageService,
public ChatSystemService: ChatSystemService,
private activatedRoute: ActivatedRoute,
private eventTriger: EventTrigger,
private RochetChatConnectorService: RochetChatConnectorService,
private zone: NgZone,
public RouteService: RouteService,
private store: Store<{ chat: RoomRemoteDataSourceState }>,
@@ -344,6 +340,8 @@ export class ChatPage implements OnInit {
this.showGroupContacts = true;
}
}
openMessagesPage(rid) {
console.log('rid', rid);
@@ -490,7 +488,7 @@ export class ChatPage implements OnInit {
}
onSegmentChange() {
this.ChatSystemService.getAllRooms();
// this.ChatSystemService.getAllRooms();
this.ChatSystemService._dm
}
@@ -48,13 +48,13 @@ export class GroupContactsPage implements OnInit {
)
{
this.textSearch="";
this.dm=null;
this.room=null;
this.isGroupCreated = this.navParams.get('isCreated');
this.groupName = this.navParams.get('name');
this.room = this.navParams.get('room');
this.members = this.navParams.get('members');
// this.textSearch="";
// this.dm=null;
// this.room=null;
// this.isGroupCreated = this.navParams.get('isCreated');
// this.groupName = this.navParams.get('name');
// this.room = this.navParams.get('room');
// this.members = this.navParams.get('members');
}
ngOnInit() {
@@ -66,59 +66,59 @@ export class GroupContactsPage implements OnInit {
}
loadUsers(){
this.options = {
headers: this.headers,
};
this.chatService.getAllUsers().subscribe((res:any)=>{
if(this.members) {
this.contacts = res.users.filter(f => !this.members.some(item => item._id === f._id));
}
else{
this.contacts = res.users.filter(data => data.username != this.sessionStore.user.UserName);
}
this.users = this.contacts.sort((a,b) => {
if(a.name < b.name){
return -1;
}
if(a.name > b.name){
return 1;
}
return 0;
});
// this.options = {
// headers: this.headers,
// };
// this.chatService.getAllUsers().subscribe((res:any)=>{
// if(this.members) {
// this.contacts = res.users.filter(f => !this.members.some(item => item._id === f._id));
// }
// else{
// this.contacts = res.users.filter(data => data.username != this.sessionStore.user.UserName);
// }
// this.users = this.contacts.sort((a,b) => {
// if(a.name < b.name){
// return -1;
// }
// if(a.name > b.name){
// return 1;
// }
// return 0;
// });
for( const user of this.users) {
// for( const user of this.users) {
const foundUser = this.objectUserSingleStone.find( e => e.name == user.name)
// const foundUser = this.objectUserSingleStone.find( e => e.name == user.name)
if(!foundUser) {
this.objectUserSingleStone.push(user)
} else {
'not found'
}
// if(!foundUser) {
// this.objectUserSingleStone.push(user)
// } else {
// 'not found'
// }
}
// }
const userContainer = {}
for(const user of this.objectUserSingleStone) {
const firstLetter = user.name.charAt(0)
// const userContainer = {}
// for(const user of this.objectUserSingleStone) {
// const firstLetter = user.name.charAt(0)
if(!userContainer[firstLetter]) {
userContainer[firstLetter] = [user]
} else {
userContainer[firstLetter].push(user)
}
// if(!userContainer[firstLetter]) {
// userContainer[firstLetter] = [user]
// } else {
// userContainer[firstLetter].push(user)
// }
}
// }
this.userContainer = userContainer
// this.userContainer = userContainer
this.showLoader = false;
});
// this.showLoader = false;
// });
}
getMembers(){
@@ -16,7 +16,7 @@ import { EventPerson } from 'src/app/models/eventperson.model';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { ThemeService } from 'src/app/services/theme.service'
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { ChatSystemService } from 'src/app/services/chat/chat-system.service';
//import { ChatSystemService } from 'src/app/services/chat/chat-system.service';
import { FileType } from 'src/app/models/fileType';
import { Storage } from '@ionic/storage';
@@ -101,7 +101,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
public ThemeService: ThemeService,
private changeDetectorRef: ChangeDetectorRef,
private platform: Platform,
public ChatSystemService: ChatSystemService,
//public ChatSystemService: ChatSystemService,
private storage: Storage,
private CameraService: CameraService,
private sanitiser: DomSanitizer,
@@ -110,60 +110,60 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
public RouteService: RouteService,
private FileValidatorService: FileValidatorService,
) {
this.ChatSystemService.getUser()
// this.ChatSystemService.getUser()
this.loggedUserChat = SessionStore.user.ChatData['data'];
this.isGroupCreated = true;
this.roomId = this.navParams.get('roomId');
window.onresize = (event) => {
if (window.innerWidth > 701) {
this.modalController.dismiss();
}
};
// this.loggedUserChat = SessionStore.user.ChatData['data'];
// this.isGroupCreated = true;
// this.roomId = this.navParams.get('roomId');
// window.onresize = (event) => {
// if (window.innerWidth > 701) {
// this.modalController.dismiss();
// }
// };
this.open();
// this.open();
setTimeout(() => {
this.scrollToBottomClicked()
}, 50)
// setTimeout(() => {
// this.scrollToBottomClicked()
// }, 50)
this.showAvatar = false
// this.showAvatar = false
setTimeout(() => {
this.scrollToBottomClicked()
this.showAvatar = true
}, 150)
// setTimeout(() => {
// this.scrollToBottomClicked()
// this.showAvatar = true
// }, 150)
}
open() {
try {
this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({});
this.ChatSystemService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked;
this.ChatSystemService.openRoom(this.roomId)
this.groupNameFormart = this.ChatSystemService.getGroupRoom(this.roomId).name.split('-').join(' ')
} catch (error) {
setTimeout(() => {
this.open()
}, 3000)
}
// try {
// this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({});
// this.ChatSystemService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked;
// this.ChatSystemService.openRoom(this.roomId)
// this.groupNameFormart = this.ChatSystemService.getGroupRoom(this.roomId).name.split('-').join(' ')
// } catch (error) {
// setTimeout(() => {
// this.open()
// }, 3000)
// }
}
ngOnInit() {
this.loggedUser = this.loggedUserChat;
this.getRoomInfo();
this.scrollToBottom();
this.serverLongPull();
this.setStatus('online');
this.getChatMembers();
// this.loggedUser = this.loggedUserChat;
// this.getRoomInfo();
// this.scrollToBottom();
// this.serverLongPull();
// this.setStatus('online');
// this.getChatMembers();
// this.getRoomMessageDB(this.roomId);
this.getGroupContacts({});
// // this.getRoomMessageDB(this.roomId);
// this.getGroupContacts({});
}
@@ -178,8 +178,8 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
deleteMessage(msgId: string) {
const room = this.ChatSystemService.getGroupRoom(this.roomId)
this.alertService.confirmDeleteMessage(msgId, room);
// const room = this.ChatSystemService.getGroupRoom(this.roomId)
// this.alertService.confirmDeleteMessage(msgId, room);
}
ngAfterViewInit() {
@@ -394,35 +394,35 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
// this.getGroupContacts(this.room);
// this.showLoader = false;
// });
this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({});
let room = await this.chatService.getRoomInfo(this.roomId).toPromise();
// console.log('ROOM',room)
this.room = room['room'];
if (this.room.name) {
try {
this.roomName = this.room.name.split('-').join(' ');
} catch (error) {
this.roomName = this.room.name;
}
// this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({});
// let room = await this.chatService.getRoomInfo(this.roomId).toPromise();
// // console.log('ROOM',room)
// this.room = room['room'];
// if (this.room.name) {
// try {
// this.roomName = this.room.name.split('-').join(' ');
// } catch (error) {
// this.roomName = this.room.name;
// }
}
// }
if (SessionStore.user.ChatData.data.userId == this.room.u._id) {
this.isAdmin = true
} else {
this.isAdmin = false
}
// if (SessionStore.user.ChatData.data.userId == this.room.u._id) {
// this.isAdmin = true
// } else {
// this.isAdmin = false
// }
if (this.room.customFields.countDownDate) {
this.roomCountDownDate = this.room.customFields.countDownDate;
}
// if (this.room.customFields.countDownDate) {
// this.roomCountDownDate = this.room.customFields.countDownDate;
// }
}
async getChatMembers() {
if(this.ChatSystemService.users.length == 0) {
this.ChatSystemService.getUser()
}
// if(this.ChatSystemService.users.length == 0) {
// this.ChatSystemService.getUser()
// }
}
/* load(){
@@ -459,7 +459,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
// });
// }
this.members = this.ChatSystemService.getGroupRoom(this.roomId).members
// this.members = this.ChatSystemService.getGroupRoom(this.roomId).members
}
@@ -479,7 +479,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
sendMessage() {
this.ChatSystemService.getGroupRoom(this.roomId).send({})
// this.ChatSystemService.getGroupRoom(this.roomId).send({})
}
@@ -504,22 +504,22 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getGroupRoom(roomId).send({
file: {
"type": "application/audio",
"msDuration": audioFile.value.msDuration,
"mimeType": audioFile.value.mimeType,
},
attachments: [{
"title": sanitize(fileName),
"title_link_download": true,
"type": "audio"
}],
temporaryData: formData,
attachmentsModelData: {
fileBase64: encodedData,
}
})
// this.ChatSystemService.getGroupRoom(roomId).send({
// file: {
// "type": "application/audio",
// "msDuration": audioFile.value.msDuration,
// "mimeType": audioFile.value.mimeType,
// },
// attachments: [{
// "title": sanitize(fileName),
// "title_link_download": true,
// "type": "audio"
// }],
// temporaryData: formData,
// attachmentsModelData: {
// fileBase64: encodedData,
// }
// })
});
this.deleteRecording();
@@ -543,7 +543,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
modal.onDidDismiss().then(res => {
if (res.data == 'leave') {
this.close()
this.ChatSystemService.deleteRoom(this.roomId)
// this.ChatSystemService.deleteRoom(this.roomId)
//this.ChatSystemService.subscribeToRoomUpdate(this.roomId, this.room);
}
else if (res.data == 'cancel') {
@@ -556,7 +556,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.addContacts();
} else if (res.data == 'delete') {
this.close()
this.ChatSystemService.deleteRoom(this.roomId)
// this.ChatSystemService.deleteRoom(this.roomId)
}
});
}
@@ -685,21 +685,21 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getGroupRoom(roomId).send({
file: {
"type": "application/img",
"guid": ''
},
attachments: [{
"title": "file.jpg",
"text": "description",
"title_link_download": false,
}],
temporaryData: formData,
attachmentsModelData: {
fileBase64: imageBase64,
}
})
// this.ChatSystemService.getGroupRoom(roomId).send({
// file: {
// "type": "application/img",
// "guid": ''
// },
// attachments: [{
// "title": "file.jpg",
// "text": "description",
// "title_link_download": false,
// }],
// temporaryData: formData,
// attachmentsModelData: {
// fileBase64: imageBase64,
// }
// })
}
@@ -750,21 +750,21 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
const formData = new FormData();
formData.append("blobFile", blob);
this.ChatSystemService.getGroupRoom(roomId).send({
file: {
"type": "application/img",
"guid": ''
},
temporaryData: formData,
attachments: [{
"title": file.path,
"text": "description",
"title_link_download": false,
}],
attachmentsModelData: {
fileBase64: imageBase64,
}
})
// this.ChatSystemService.getGroupRoom(roomId).send({
// file: {
// "type": "application/img",
// "guid": ''
// },
// temporaryData: formData,
// attachments: [{
// "title": file.path,
// "text": "description",
// "title_link_download": false,
// }],
// attachmentsModelData: {
// fileBase64: imageBase64,
// }
// })
}
@@ -784,28 +784,28 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
if (data.selected) {
this.ChatSystemService.getGroupRoom(this.roomId).send({
file: {
"name": res.data.selected.Assunto,
"type": "application/webtrix",
"ApplicationId": res.data.selected.ApplicationType,
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
},
temporaryData: res,
attachments: [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
// "title_link": url_no_options,
"title_link_download": true,
//"thumb_url": "assets/images/webtrix-logo.png",
// "message_link": url_no_options,
"type": "webtrix",
//"thumb_url": "assets/images/webtrix-logo.png",
"text": res.data.selected.DocTypeDesc,
"thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png",
}]
})
// this.ChatSystemService.getGroupRoom(this.roomId).send({
// file: {
// "name": res.data.selected.Assunto,
// "type": "application/webtrix",
// "ApplicationId": res.data.selected.ApplicationType,
// "DocId": res.data.selected.Id,
// "Assunto": res.data.selected.Assunto,
// },
// temporaryData: res,
// attachments: [{
// "title": res.data.selected.Assunto,
// "description": res.data.selected.DocTypeDesc,
// // "title_link": url_no_options,
// "title_link_download": true,
// //"thumb_url": "assets/images/webtrix-logo.png",
// // "message_link": url_no_options,
// "type": "webtrix",
// //"thumb_url": "assets/images/webtrix-logo.png",
// "text": res.data.selected.DocTypeDesc,
// "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png",
// }]
// })
}
});
@@ -848,22 +848,22 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
formDataa.append('blobFile', blobb);
/* console.log('add file', fileBase64) */
this.ChatSystemService.getGroupRoom(roomId).send({
file: {
"type": resultt.files[0].mimeType,
"guid": '',
},
attachments: [{
"title": sanitize(resultt.files[0].name),
"name": sanitize(resultt.files[0].name),
// "text": "description",
"title_link_download": false,
}],
temporaryData: formDataa,
attachmentsModelData: {
fileBase64: '',
}
})
// this.ChatSystemService.getGroupRoom(roomId).send({
// file: {
// "type": resultt.files[0].mimeType,
// "guid": '',
// },
// attachments: [{
// "title": sanitize(resultt.files[0].name),
// "name": sanitize(resultt.files[0].name),
// // "text": "description",
// "title_link_download": false,
// }],
// temporaryData: formDataa,
// attachmentsModelData: {
// fileBase64: '',
// }
// })
return
}
@@ -888,22 +888,22 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
formData.append('blobFile', blob);
this.ChatSystemService.getGroupRoom(roomId).send({
file: {
"type": file.type,
"guid": '',
},
attachments: [{
"title": sanitize(fileName),
"name": sanitize(fileName),
// "text": "description",
"title_link_download": false,
}],
temporaryData: formData,
attachmentsModelData: {
fileBase64: encodedData
}
});
// this.ChatSystemService.getGroupRoom(roomId).send({
// file: {
// "type": file.type,
// "guid": '',
// },
// attachments: [{
// "title": sanitize(fileName),
// "name": sanitize(fileName),
// // "text": "description",
// "title_link_download": false,
// }],
// temporaryData: formData,
// attachmentsModelData: {
// fileBase64: encodedData
// }
// });
} else {
@@ -980,7 +980,8 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
componentProps: {
isCreated: this.isGroupCreated,
room: this.room,
members: this.ChatSystemService.getGroupRoom(this.roomId).members,
//members: this.ChatSystemService.getGroupRoom(this.roomId).members,
members: [],
name: this.room.name,
},
cssClass: 'contacts',
@@ -16,7 +16,7 @@ export class MessageRemoteDataSourceService {
constructor(private httpService: HttpService) {}
@APIReturn(MessageOutPutDTOSchema)
@APIReturn(MessageOutPutDTOSchema, 'get/Messages')
@ValidateSchema(MessageInputDTOSchema)
async sendMessage(data: MessageInputDTO) {
return await this.httpService.post<MessageOutPutDTO>(`${this.baseUrl}/Messages`, data);
@@ -23,19 +23,19 @@ export class RoomRemoteDataSourceService {
@ValidateSchema(RoomInputDTOSchema)
@APIReturn(RoomOutPutDTOSchema)
@APIReturn(RoomOutPutDTOSchema, 'post/Room')
async createRoom(data: RoomInputDTO): DataSourceReturn<RoomOutPutDTO> {
return await this.httpService.post<RoomOutPutDTO>(`${this.baseUrl}/Room`, data);
}
@APIReturn(RoomListOutPutDTOSchema)
@APIReturn(RoomListOutPutDTOSchema, 'get/Room')
async getRoomList(): Promise<DataSourceReturn<RoomListOutPutDTO>> {
return await this.httpService.get<RoomListOutPutDTO>(`${this.baseUrl}/Room`);
}
@ValidateSchema(RoomByIdInputDTOSchema)
@APIReturn(RoomByIdOutputDTOSchema)
@APIReturn(RoomByIdOutputDTOSchema,'get/Room/${id}')
async getRoom(id: RoomByIdInputDTO): DataSourceReturn<RoomByIdOutputDTO> {
return await this.httpService.get(`${this.baseUrl}/Room/${id}`);
}
@@ -58,6 +58,16 @@ export class RoomLocalDataSourceService {
}
}
async deleteRoomById(id: string) {
try {
const result = await roomDataSource.room.delete(id)
return ok(result)
} catch (e) {
return err(false)
}
}
async updateRoom(data: TableRoom) {
try {
const result = await roomDataSource.room.update(data.id, data);
@@ -4,7 +4,8 @@ export const RoomInputDTOSchema = z.object({
roomName: z.string(),
createdBy: z.number(),
roomType: z.number(),
expirationDate: z.string().datetime().nullable()
expirationDate: z.string().datetime().nullable(),
members: z.array(z.number())
});
@@ -1,14 +1,14 @@
import { z } from "zod";
export const RoomOutPutDTOSchema = z.object({
success: z.string(),
success: z.boolean(),
message: z.string(),
data: z.object({
id: z.string(),
roomName: z.string(),
createdBy: z.any(),
createdAt: z.date(),
expirationDate: z.date(),
createdAt: z.string(),
expirationDate: z.string().nullable(),
roomType: z.any()
})
});
@@ -9,6 +9,7 @@ import { RoomByIdInputDTO } from '../dto/room/roomByIdInputDTO';
import { roomListDetermineChanges } from '../async/rooms/roomListChangeDetector';
import { UserRemoveListInputDTO } from '../dto/room/userRemoveListInputDTO';
import { roomMemberListDetermineChanges } from '../async/rooms/roomMembersChangeDetector';
import { captureAndReraiseAsync } from 'src/app/services/decorators/captureAndReraiseAsync';
@Injectable({
providedIn: 'root'
@@ -21,6 +22,7 @@ export class RoomRepositoryService {
private roomLocalDataSourceService: RoomLocalDataSourceService
) { }
@captureAndReraiseAsync('RoomRepositoryService/list')
async list() {
const result = await this.roomRemoteDataSourceService.getRoomList()
@@ -33,15 +35,25 @@ export class RoomRepositoryService {
if(result.isOk()) {
const { roomsToDelete, roomsToInsert, roomsToUpdate } = roomListDetermineChanges(result.value.data, localList)
console.log({ roomsToDelete, roomsToInsert, roomsToUpdate })
console.log({roomsToDelete, roomsToInsert, roomsToUpdate})
for( const roomData of roomsToInsert) {
this.roomLocalDataSourceService.createOrUpdateRoom(roomData)
this.roomLocalDataSourceService.createRoom(roomData)
}
for( const roomData of roomsToUpdate) {
this.roomLocalDataSourceService.updateRoom(roomData)
}
for( const roomData of roomsToDelete) {
this.roomLocalDataSourceService.deleteRoomById(roomData.id)
}
}
return result
}
@captureAndReraiseAsync('RoomRepositoryService/getRoomById')
async getRoomById(id: RoomByIdInputDTO) {
const result = await this.roomRemoteDataSourceService.getRoom(id)
@@ -50,6 +62,13 @@ export class RoomRepositoryService {
const { membersToInsert, membersToUpdate, membersToDelete } = roomMemberListDetermineChanges(result.value.data.members, localList, id)
const a = await this.roomLocalDataSourceService.createOrUpdateRoom(result.value.data)
if(a.isErr()) {
return a
}
for (const user of membersToInsert) {
this.roomLocalDataSourceService.addMember({...user, roomId:id})
}
@@ -63,6 +82,7 @@ export class RoomRepositoryService {
return result
}
@captureAndReraiseAsync('RoomRepositoryService/create')
async create(data: RoomInputDTO) {
const result = await this.roomRemoteDataSourceService.createRoom(data)
+133 -133
View File
@@ -73,122 +73,122 @@ export class ChatSystemService {
) {
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.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();
//
// this.RochetChatConnectorService.setStatus('online')
// this.getUserStatus();
// await this.chatService.refreshtoken();
// this.getUser();
// this.getAllRooms();
// this.subscribeToRoom();
// //
if (this.currentRoom) {
this.currentRoom.loadHistory({ forceUpdate: true })
}
// if (this.currentRoom) {
// this.currentRoom.loadHistory({ forceUpdate: true })
// }
for (const id in this.dm) {
this.dm[id].hasLoadHistory = false
}
// for (const id in this.dm) {
// this.dm[id].hasLoadHistory = false
// }
for (const id in this.group) {
this.group[id].hasLoadHistory = false
}
// for (const id in this.group) {
// this.group[id].hasLoadHistory = false
// }
}
})
// }
// })
if (this.sessionStore.user.Inactivity) {
this.loadChat();
}
// if (this.sessionStore.user.Inactivity) {
// this.loadChat();
// }
if (SessionStore.user?.ChatData?.data) {
this.restoreRooms();
}
// 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();
}
// 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');
// 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 })
}
// if (SessionStore.user?.ChatData?.data) {
// this.currentRoom?.loadHistory({ forceUpdate: true })
// }
setTimeout(() => {
if (SessionStore.user?.ChatData?.data) {
this.subscribeToRoom()
this.RochetChatConnectorService.setStatus('online')
}
}, 1000);
// 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) {}
// /* 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()
}
// if (SessionStore.user?.ChatData?.data) {
// this.ReLoadChat()
// }
}
private async ReLoadChat() {
if (SessionStore.user?.ChatData?.data) {
this.getUserStatus();
await this.chatService.refreshtoken();
// if (SessionStore.user?.ChatData?.data) {
// this.getUserStatus();
// await this.chatService.refreshtoken();
this.restoreUsers();
await this.getUser();
await this.restoreRooms();
await this.getAllRooms();
this.subscribeToRoom();
}
// this.restoreUsers();
// await this.getUser();
// await this.restoreRooms();
// await this.getAllRooms();
// this.subscribeToRoom();
// }
//
}
clearChat() {
this.dm = {}
this.group = {}
this._dm = []
this._group = []
// this.dm = {}
// this.group = {}
// this._dm = []
// this._group = []
this.loadingWholeList = false;
// this.loadingWholeList = false;
this.dmCount = 0;
this.groupCount = 0;
// this.dmCount = 0;
// this.groupCount = 0;
this.currentRoom = null
this.users = []
this.storage.remove('Users');
// this.currentRoom = null
// this.users = []
// this.storage.remove('Users');
}
openRoom(roomId) {
@@ -217,15 +217,15 @@ export class ChatSystemService {
async restoreRooms() {
try {
const _rooms = await this.storage.get('Rooms');
// try {
// const _rooms = await this.storage.get('Rooms');
if (_rooms) {
for (let roomData of this.sortArrayISODate(_rooms)) {
await this.prepareRoom(roomData);
}
}
} catch (e) { }
// if (_rooms) {
// for (let roomData of this.sortArrayISODate(_rooms)) {
// await this.prepareRoom(roomData);
// }
// }
// } catch (e) { }
}
@@ -358,27 +358,27 @@ export class ChatSystemService {
*/
subscribeToRoom() {
if (SessionStore.user?.ChatData?.data) {
// if (SessionStore.user?.ChatData?.data) {
for (const id in this.dm) {
this.defaultSubtribe(id)
}
// for (const id in this.dm) {
// this.defaultSubtribe(id)
// }
for (const id in this.group) {
this.defaultSubtribe(id)
}
// for (const id in this.group) {
// this.defaultSubtribe(id)
// }
this.RochetChatConnectorService.streamNotifyLogged().then((subscription => { }))
// this.RochetChatConnectorService.streamNotifyLogged().then((subscription => { }))
this.RochetChatConnectorService.subStreamMessageUser().then((subscription => {
console.log({subscription})
}))
} else {
// this.RochetChatConnectorService.subStreamMessageUser().then((subscription => {
// console.log({subscription})
// }))
// } else {
setTimeout(() => {
throw ('No chat data');
}, 1000)
}
// setTimeout(() => {
// throw ('No chat data');
// }, 1000)
// }
}
@@ -389,11 +389,11 @@ export class ChatSystemService {
*/
subscribeToRoomUpdate(id, roomData) {
this.defaultSubtribe(id);
// this.defaultSubtribe(id);
this.prepareRoom(roomData);
// this.prepareRoom(roomData);
this.getGroupRoom(id).loadHistory({});
// this.getGroupRoom(id).loadHistory({});
}
@@ -404,35 +404,35 @@ export class ChatSystemService {
*/
private defaultSubtribe(id: any) {
const room = this.getRoomById(id);
// const room = this.getRoomById(id);
if (!room.subscribeAttempt) {
// if (!room.subscribeAttempt) {
try {
// try {
room.subscribeAttempt = true;
} catch (error) {
console.log("error")
}
// room.subscribeAttempt = true;
// } catch (error) {
// console.log("error")
// }
this.RochetChatConnectorService.streamRoomMessages(id).then((subscription) => {
room.status.receive.message = true;
})
// 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, 'typing', false).then((subscription) => {
// room.status.receive.typing = true;
// //
// })
this.RochetChatConnectorService.subStreamNotifyRoom(id, 'readMessage', false).then((subscription) => {
room.status.receive.readMessage = 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;
})
}
// this.RochetChatConnectorService.streamNotifyRoomDeleteMessage(id).then((subscription) => {
// room.status.receive.deleteMessage = true;
// })
// }
}
@@ -51,7 +51,7 @@ export class RochetChatConnectorService {
}
wsSend({ message, requestId = uuidv4(), loginRequired = true }: send) {
this.ws.send({ message: { msg: "pong" }, loginRequired: false })
// this.ws.send({ message: { msg: "pong" }, loginRequired: false })
}
login() {
@@ -225,7 +225,7 @@ export class RochetChatConnectorService {
//
this.ws.send({ message, requestId });
// this.ws.send({ message, requestId });
return new Promise((resolve, reject) => {
this.ws.registerCallback({
+46 -46
View File
@@ -1231,66 +1231,66 @@ export class RoomService {
async updateContacts() {
let res
let error = false
// let res
// let error = false
if (this.t == 'd') {
// if (this.t == 'd') {
try {
res = await this.chatService.getMembers(this.id).toPromise();
} catch (e) {
await this.chatService.refreshtoken();
error = true
}
// try {
// res = await this.chatService.getMembers(this.id).toPromise();
// } catch (e) {
// await this.chatService.refreshtoken();
// error = true
// }
if (error) {
res = await this.chatService.getMembers(this.id).toPromise();
}
// if (error) {
// res = await this.chatService.getMembers(this.id).toPromise();
// }
} else {
if (this.t === 'p') {
// } else {
// if (this.t === 'p') {
try {
res = await this.chatService.getGroupMembers(this.id).toPromise()
} catch (e) {
await this.chatService.refreshtoken();
error = true
}
// try {
// res = await this.chatService.getGroupMembers(this.id).toPromise()
// } catch (e) {
// await this.chatService.refreshtoken();
// error = true
// }
if (error) {
res = await this.chatService.getGroupMembers(this.id).toPromise()
}
// if (error) {
// res = await this.chatService.getGroupMembers(this.id).toPromise()
// }
setTimeout(() => {
// console.log("getGroupMembers", this.membersExcludeMe)
}, 500)
// setTimeout(() => {
// // console.log("getGroupMembers", this.membersExcludeMe)
// }, 500)
}
else {
// }
// else {
try {
res = await this.chatService.getChannelMembers(this.id).toPromise()
// try {
// res = await this.chatService.getChannelMembers(this.id).toPromise()
} catch (e) {
await this.chatService.refreshtoken();
error = true
}
// } catch (e) {
// await this.chatService.refreshtoken();
// error = true
// }
if (error) {
res = await this.chatService.getChannelMembers(this.id).toPromise()
}
// if (error) {
// res = await this.chatService.getChannelMembers(this.id).toPromise()
// }
setTimeout(() => {
console.log("getChannelMembers", this.membersExcludeMe)
}, 500)
}
}
// setTimeout(() => {
// console.log("getChannelMembers", this.membersExcludeMe)
// }, 500)
// }
// }
const members = res['members'];
const users = members.filter(data => data.username != this.sessionStore.user.UserName);
this.members = members
this.membersExcludeMe = users
// const members = res['members'];
// const users = members.filter(data => data.username != this.sessionStore.user.UserName);
// this.members = members
// this.membersExcludeMe = users
}
async closeModal() {
@@ -1,9 +1,10 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Result, err } from 'neverthrow';
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) {
export function APIReturn(schema: z.ZodTypeAny, context: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
@@ -19,9 +20,8 @@ export function APIReturn(schema: z.ZodTypeAny) {
if (error instanceof ZodError) {
// If validation fails, throw an error with the details
//
console.error('API unexpected data structure')
console.error(result.value)
console.error(error.errors)
ColoredLoggerService.error(error.errors, 'API unexpected data structure '+ context, schema._def.description)
// Capture the Zod validation error with additional context
Sentry.withScope((scope) => {
scope.setTag('APIReturn', 'user');
@@ -0,0 +1,19 @@
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)
// Re-throw the same error
return err(error) ;
}
};
return descriptor;
};
}
+53
View File
@@ -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,
);
}
}
@@ -0,0 +1,69 @@
import { DateUtils } from './date';
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}`;
}
export class ColoredLoggerService {
constructor() {}
static log(message: string): void {
console.log(
`[${getCurrentTime()}] %cINFO : `, // Console Message
'color: #00897B', // CSS Style
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 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 warn({ message, context, obj = {} }: MessageType): void {
console.warn(
`[${getCurrentTime()}] %cWARN : `, // Console Message
'color: #FB8C00', // CSS Style
Object.assign(obj, { context, createdAt: DateUtils.getISODateString(), message })
);
}
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?: any, message?: string, context?: string): void {}
}
+12
View File
@@ -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;
}
@@ -102,15 +102,15 @@ export class ViewEventPage implements OnInit {
}
async openNewGroupPage() {
let roomName = this.loadedEvent.Subject
let attendees = this.loadedEvent.Attendees
// async openNewGroupPage() {
// let roomName = this.loadedEvent.Subject
// let attendees = this.loadedEvent.Attendees
const room = await EventController.createOrFindGroupFromEvent(roomName, attendees)
// const room = await EventController.createOrFindGroupFromEvent(roomName, attendees)
let navigationExtras: NavigationExtras = { queryParams: { "roomId": room.id } };
this.router.navigate(['/home/chat'], navigationExtras);
}
// let navigationExtras: NavigationExtras = { queryParams: { "roomId": room.id } };
// this.router.navigate(['/home/chat'], navigationExtras);
// }
close() {
@@ -14,7 +14,7 @@
</div>
<div>
<button class="btn-no-color adicionar" (click)="updateGroup()">
<ion-label>Adicionar</ion-label>
<ion-label>Adicionar bug</ion-label>
</button>
</div>
</div>
@@ -9,6 +9,7 @@ import { HttpErrorHandle } from 'src/app/services/http-error-handle.service';
import { SessionStore } from 'src/app/store/session.service';
import { HttpRequest } from '@angular/common/http';
import { ZodError } from 'zod';
import { HttpResponse } from '@microsoft/signalr';
@Component({
selector: 'app-group-contacts',
@@ -22,6 +23,8 @@ export class GroupContactsPage implements OnInit {
@Input() roomId:string;
@Output() openGroupMessage:EventEmitter<any> = new EventEmitter<any>();
@Output() openGroupContacts:EventEmitter<any> = new EventEmitter<any>();
currentMembers:UserContacts[];
allChatUsers: UserContacts[] = [];
@@ -99,10 +102,12 @@ export class GroupContactsPage implements OnInit {
}))
}
else if (getRoomById.isErr()) {
else if (getRoomById.isErr() && getRoomById.error instanceof HttpResponse) {
this.httpErrorHandle.httpStatusHandle(getRoomById.error)
} else if (getallChatUsers.isErr()) {
} else if (getallChatUsers.isErr() && getallChatUsers.error instanceof HttpResponse) {
this.httpErrorHandle.httpStatusHandle(getallChatUsers.error)
} else {
alert('else')
}
const currentMemberIds = this.currentMembers.map(e => e.wxUserId)
@@ -31,19 +31,19 @@
<div class="main-content">
<ion-progress-bar class="position-absolute" type="indeterminate" *ngIf="loading"></ion-progress-bar>
<ion-virtual-scroll [items]="userList" approxItemHeight="70px" [headerFn]="separateLetter">
<div class="item-divider" *virtualHeader="let header">
<ion-label>{{ header }}</ion-label>
</div>
<div (click)="openMessagesPage(user.wxFullName)" *virtualItem="let user" class="item-user cursor-pointer">
<p>{{ user.wxFullName }}</p>
<span class="icon">
<ion-icon [class]="user.status" slot="end" name="ellipse"></ion-icon>
</span>
</div>
</ion-virtual-scroll>
</div>
</ion-content>
@@ -4,11 +4,12 @@ import { ChatSystemService } from 'src/app/services/chat/chat-system.service';
import { DataService } from 'src/app/services/data.service';
import { GroupDurationPage } from 'src/app/shared/popover/group-duration/group-duration.page';
import { SessionStore } from 'src/app/store/session.service';
import { ToastService } from 'src/app/services/toast.service';
import { ThemeService } from 'src/app/services/theme.service';
import { RouteService } from 'src/app/services/route.service';
import { HttpErrorResponse } from '@angular/common/http';
import { RoomRepositoryService } from 'src/app/services/Repositorys/chat/repository/room-repository.service';
import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'
@Component({
selector: 'app-new-group',
templateUrl: './new-group.page.html',
@@ -49,7 +50,8 @@ export class NewGroupPage implements OnInit{
public ThemeService: ThemeService,
private RouteService: RouteService,
private viewContainerRef: ViewContainerRef,
private roomRepositoryService: RoomRepositoryService
private roomRepositoryService: RoomRepositoryService,
private httpErrorHandle: HttpErrorHandle,
)
{
this.loggedUserChat = SessionStore.user.ChatData['data'];
@@ -121,13 +123,15 @@ export class NewGroupPage implements OnInit{
roomName: this.groupName,
createdBy: SessionStore.user.UserId,
roomType: 0,
expirationDate: null
expirationDate: null,
members: []
})
if(result.isOk()) {
// this.addGroupMessage.emit(result);
this.addGroupMessage.emit(result.value.data.id);
} else if(result.error instanceof HttpErrorResponse) {
this.httpErrorHandle.httpStatusHandle(result.error)
}
}