fix message

This commit is contained in:
Peter Maquiran
2024-09-05 11:45:54 +01:00
parent 106267aee9
commit b0e1dd74cd
16 changed files with 237 additions and 78 deletions
+14 -12
View File
@@ -19,6 +19,19 @@ export enum IMessageType {
information information
} }
export const MessageEntityAttachmentSchema = z.object({
fileType: z.nativeEnum(MessageAttachmentFileType),
source: z.nativeEnum(MessageAttachmentSource),
file: base64Schema.optional(),
fileName: z.string().optional(),
applicationId: z.number().optional(),
docId: z.string().optional(),
id: z.string().optional(),
mimeType: z.string().optional(),
safeFile: z.any().optional(),
description: z.string().nullable().optional()
})
export const MessageEntitySchema = z.object({ export const MessageEntitySchema = z.object({
$id: z.any().optional(), $id: z.any().optional(),
id: z.string().uuid().optional(), id: z.string().uuid().optional(),
@@ -50,18 +63,7 @@ export const MessageEntitySchema = z.object({
deliverAt: z.string().nullable() deliverAt: z.string().nullable()
})).optional(), })).optional(),
sending: z.boolean().optional(), sending: z.boolean().optional(),
attachments: z.array(z.object({ attachments: z.array(MessageEntityAttachmentSchema).optional(),
fileType: z.nativeEnum(MessageAttachmentFileType),
source: z.nativeEnum(MessageAttachmentSource),
file: base64Schema.optional(),
fileName: z.string().optional(),
applicationId: z.number().optional(),
docId: z.string().optional(),
id: z.string().optional(),
mimeType: z.string().optional(),
safeFile: z.any().optional(),
description: z.string().nullable().optional()
})).optional(),
origin: z.enum(['history', 'local', 'incoming']).optional(), origin: z.enum(['history', 'local', 'incoming']).optional(),
requestId: z.string().optional(), requestId: z.string().optional(),
sendAttemp: z.number().optional(), sendAttemp: z.number().optional(),
@@ -7,11 +7,11 @@ export const AttachmentTableSchema = z.object({
$id: z.number().optional(), // local id $id: z.number().optional(), // local id
$messageId: z.string(), $messageId: z.string(),
attachmentId: z.string().optional(), attachmentId: z.string().optional(),
file: z.instanceof(Blob), file: z.instanceof(Blob).optional(),
base64: zodDataUrlSchema.nullable().optional(), base64: zodDataUrlSchema.nullable().optional(),
// //
fileType: z.nativeEnum(MessageAttachmentFileType), fileType: z.nativeEnum(MessageAttachmentFileType).optional(),
source: z.nativeEnum(MessageAttachmentSource), source: z.nativeEnum(MessageAttachmentSource).optional(),
fileName: z.string().optional(), fileName: z.string().optional(),
applicationId: z.number().optional(), applicationId: z.number().optional(),
docId: z.string().optional(), docId: z.string().optional(),
@@ -49,5 +49,5 @@ export const MessageTableSchema = z.object({
export type MessageTable = z.infer<typeof MessageTableSchema> export type MessageTable = z.infer<typeof MessageTableSchema>
export type DexieMessageTable = EntityTable<MessageTable, '$id'>; export type DexieMessageTable = EntityTable<MessageTable, '$id'>;
export const messageTableColumn = '$id, id, roomId, senderId, message, messageType, canEdit, oneShot, requireUnlock' export const messageTableColumn = '$id, id, roomId, senderId, message, messageType, canEdit, oneShot, requireUnlock, sending'
+3 -1
View File
@@ -1,11 +1,13 @@
import { Result } from 'neverthrow'; import { Result } from 'neverthrow';
import { ZodError} from 'zod'; import { ZodError} from 'zod';
import { IDBError } from './types'; import { IDBError } from './types';
import Dexie, { EntityTable, Table } from 'Dexie';
// Define a type for the Result of repository operations // Define a type for the Result of repository operations
export type RepositoryResult<T, E> = Result<T, IDBError<E>>; export type RepositoryResult<T, E> = Result<T, IDBError<E>>;
export abstract class IDexieRepository<T, R> { export abstract class IDexieRepository<T, R, I = EntityTable<any, any>> {
abstract createTransaction(callback: (table: I) => Promise<void>): Promise<void>
abstract insert(document: T): Promise<RepositoryResult<number, T>> abstract insert(document: T): Promise<RepositoryResult<number, T>>
abstract insertMany(documents: T[]): Promise<RepositoryResult<number[], T[]>> abstract insertMany(documents: T[]): Promise<RepositoryResult<number[], T[]>>
@@ -1,5 +1,5 @@
import { Result, ok, err } from 'neverthrow'; import { Result, ok, err } from 'neverthrow';
import { EntityTable } from 'Dexie'; import Dexie, { EntityTable, Table } from 'Dexie';
import { ZodError, ZodObject, ZodSchema } from 'zod'; import { ZodError, ZodObject, ZodSchema } from 'zod';
import { Logger } from 'src/app/services/logger/main/service'; import { Logger } from 'src/app/services/logger/main/service';
import { IDexieRepository, RepositoryResult } from '../adapter' import { IDexieRepository, RepositoryResult } from '../adapter'
@@ -30,17 +30,37 @@ class DBError<T> extends Error implements IDBError<T> {
} }
} }
export class DexieRepository<T, R> implements IDexieRepository<T, R> { export class DexieRepository<T, R, I = EntityTable<any, any>> implements IDexieRepository<T, R, I> {
private table: EntityTable<any, any>; private table: EntityTable<any, any>;
private ZodSchema: ZodSchema<T> private ZodSchema: ZodSchema<T>
private ZodPartialSchema: ZodSchema<T> private ZodPartialSchema: ZodSchema<T>
private db: Dexie
constructor(table: EntityTable<any, any>, ZodSchema: ZodSchema) { constructor(table: EntityTable<any, any>, ZodSchema: ZodSchema, db?:Dexie) {
this.table = table as any this.table = table as any
this.ZodSchema = ZodSchema this.ZodSchema = ZodSchema
this.ZodPartialSchema = (ZodSchema as ZodObject<any>).partial() as any; this.ZodPartialSchema = (ZodSchema as ZodObject<any>).partial() as any;
this.db = db
} }
// Method to create a transaction and use the callback
async createTransaction(callback: (table:I) => Promise<void>): Promise<void> {
return this.db.transaction('rw', this.table, async () => {
try {
// Execute the callback function
await callback(this.table as any);
} catch (error) {
// Transactions are automatically rolled back on error
throw error;
}
}).then(() => {
console.log('Transaction completed successfully');
}).catch((error) => {
console.error('Transaction failed: ' + error);
});
}
async insert(document: T): Promise<RepositoryResult<any, T>> { async insert(document: T): Promise<RepositoryResult<any, T>> {
const dataValidation = this.ZodSchema.safeParse(document) const dataValidation = this.ZodSchema.safeParse(document)
@@ -3,7 +3,7 @@ import { liveQuery } from 'Dexie';
import { MessageEntity } from '../../../../../core/chat/entity/message'; import { MessageEntity } from '../../../../../core/chat/entity/message';
import { DexieRepository } from 'src/app/infra/repository/dexie/dexie-repository.service'; import { DexieRepository } from 'src/app/infra/repository/dexie/dexie-repository.service';
import { Observable as DexieObservable, PromiseExtended } from 'Dexie'; import { Observable as DexieObservable, PromiseExtended } from 'Dexie';
import { MessageTable, MessageTableSchema } from 'src/app/infra/database/dexie/instance/chat/schema/message'; import { DexieMessageTable, MessageTable, MessageTableSchema } from 'src/app/infra/database/dexie/instance/chat/schema/message';
import { chatDatabase } from 'src/app/infra/database/dexie/service'; import { chatDatabase } from 'src/app/infra/database/dexie/service';
import { IMessageLocalRepository } from 'src/app/core/chat/repository/message/message-local-repository'; import { IMessageLocalRepository } from 'src/app/core/chat/repository/message/message-local-repository';
import { BehaviorSubject, combineLatest, from, Observable } from 'rxjs'; import { BehaviorSubject, combineLatest, from, Observable } from 'rxjs';
@@ -13,13 +13,13 @@ import { v4 as uuidv4 } from 'uuid'
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class MessageLocalDataSourceService extends DexieRepository<MessageTable, MessageEntity> implements IMessageLocalRepository { export class MessageLocalDataSourceService extends DexieRepository<MessageTable, MessageEntity, DexieMessageTable> implements IMessageLocalRepository {
private creatingSubject : BehaviorSubject<MessageTable> = new BehaviorSubject<MessageTable>(null); private creatingSubject : BehaviorSubject<MessageTable> = new BehaviorSubject<MessageTable>(null);
private lastTimestamp = 0; private lastTimestamp = 0;
constructor() { constructor() {
super(chatDatabase.message, MessageTableSchema) super(chatDatabase.message, MessageTableSchema, chatDatabase)
this.setAllSenderToFalse(); this.setAllSenderToFalse();
this.onCreatingHook() this.onCreatingHook()
@@ -54,22 +54,33 @@ export class MessageLocalDataSourceService extends DexieRepository<MessageTable,
} }
async setAllSenderToFalse() { async setAllSenderToFalse() {
// this.createTransaction(async (table) => {
// const result = await this.find({sending: true })
// if(result.isOk()) {
// for(const message of result.value) {
// await this.update(message.$id, { sending: false })
// }
// }
// })
try { try {
await chatDatabase.transaction('rw', chatDatabase.message, async () => { await chatDatabase.transaction('rw', chatDatabase.message, async () => {
// Perform the update operation within the transaction // Perform the update operation within the transaction
await chatDatabase.message.toCollection().modify({ sending: false }); await chatDatabase.message.toCollection().modify({ sending: false });
}); });
// console.log('All messages updated successfully.');
} catch (error) { } catch (error) {
console.error('Error updating messages:', error); console.error('Error updating messages:', error);
} }
} }
getItems(roomId: string): PromiseExtended<MessageEntity[]> { getItems(roomId: string): PromiseExtended<MessageEntity[]> {
return chatDatabase.message.where('roomId').equals(roomId).sortBy('$id') as any return chatDatabase.message.where('roomId').equals(roomId).sortBy('$createAt') as any
} }
getItemsLive(roomId: string): DexieObservable<MessageEntity[]> { getItemsLive(roomId: string): DexieObservable<MessageEntity[]> {
return liveQuery(() => chatDatabase.message.where('roomId').equals(roomId).sortBy('$id') as any) return liveQuery(() => chatDatabase.message.where('roomId').equals(roomId).sortBy('$createAt') as any)
} }
async getOfflineMessages () { async getOfflineMessages () {
@@ -4,6 +4,8 @@ import { Logger } from 'src/app/services/logger/main/service';
import { convertBlobToDataURL, createBlobUrl } from 'src/app/utils/ToBase64'; import { convertBlobToDataURL, createBlobUrl } from 'src/app/utils/ToBase64';
import { AttachmentLocalDataSource } from 'src/app/module/chat/data/repository/attachment/attachment-local-repository.service' import { AttachmentLocalDataSource } from 'src/app/module/chat/data/repository/attachment/attachment-local-repository.service'
import { z } from 'zod'; import { z } from 'zod';
import { zodSafeValidation } from 'src/app/utils/zodValidation';
import { IMessage, MessageEntitySchema } from 'src/app/core/chat/entity/message';
const DownloadMessageAttachmentByMessageIdSchema = z.object({ const DownloadMessageAttachmentByMessageIdSchema = z.object({
$messageId: z.string(), $messageId: z.string(),
@@ -24,28 +26,43 @@ export class DownloadMessageAttachmentUserCaseService {
) { } ) { }
async execute(input: DownloadMessageAttachmentByMessageId) { async execute(input: DownloadMessageAttachmentByMessageId) {
const result = await this.AttachmentRemoteDataSourceService.getAttachment(input.$messageId)
return result.asyncMap(async (blob) => {
const dataUrl = await createBlobUrl(blob) const validation = zodSafeValidation<IMessage>(DownloadMessageAttachmentByMessageIdSchema, input)
if(dataUrl.isOk()) { if(validation.isOk()) {
Logger.info('downloaded file #1', { const result = await this.AttachmentRemoteDataSourceService.getAttachment(input.id)
// data: dataUrl.slice(0, 100)+'...', return result.asyncMap(async (blob) => {
context: 'DownloadMessageAttachmentUserCaseService'
})
this.AttachmentLocalDataSource.insert({ const dataUrl = await createBlobUrl(blob)
$messageId: input.$messageId,
id: input.id,
file: blob
})
return dataUrl if(dataUrl.isOk()) {
} else {
Logger.info('downloaded file #1', {
// data: dataUrl.slice(0, 100)+'...',
context: 'DownloadMessageAttachmentUserCaseService'
})
this.AttachmentLocalDataSource.insert({
$messageId: input.$messageId,
id: input.id,
file: blob
})
return dataUrl.value
} else {
}
})
} else {
Logger.error('failed to download message doe to invalid attachment', {
zodErrorList: validation.error.errors,
data: input
})
return validation
}
}
})
} }
} }
@@ -72,10 +72,16 @@
</div> </div>
<div *ngIf="attachment.fileType == MessageAttachmentFileType.Image"> <div *ngIf="attachment.fileType == MessageAttachmentFileType.Image">
<img
*ngIf="message.oneShot != true && attachment.blobURl != true"
[src]="attachment.safeFile"
(load)="onImageLoad(message, messageIndex)"
(error)="onImageError()"
>
<img <img
*ngIf="message.oneShot != true" *ngIf="message.oneShot != true && attachment.blobURl"
[src]="attachment.safeFile" [src]="attachment.safeFile|safehtml"
(load)="onImageLoad(message, messageIndex)" (load)="onImageLoad(message, messageIndex)"
(error)="onImageError()" (error)="onImageError()"
> >
@@ -320,10 +320,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
// } // }
// return true; // Keep messages without an id // return true; // Keep messages without an id
// }); // });
console.time("mappingTime");
messages = messages.sort((a: any, b: any) => a.$createAt - b.$createAt)
for(const message of messages) { for(const message of messages) {
const date = whatsappDate(message.sentAt, false) const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) { if(!this.date[date]) {
@@ -334,12 +331,12 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
allMessage.push(new MessageViewModal(message)) allMessage.push(new MessageViewModal(message))
} }
console.timeEnd("mappingTime");
console.time("mappingTime");
this.messages1[this.roomId] = allMessage this.messages1[this.roomId] = allMessage
console.timeEnd("mappingTime");
// if(messages.length >= 1) { // if(messages.length >= 1) {
// this.messages1[this.roomId].push(LastMessage) // this.messages1[this.roomId].push(LastMessage)
@@ -370,13 +367,15 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
for(const message of this.messages1[this.roomId]) { for(const message of this.messages1[this.roomId]) {
if(message.hasAttachment && message.attachments[0].source != MessageAttachmentSource.Webtrix) { if(message.hasAttachment && message.attachments[0].source != MessageAttachmentSource.Webtrix) {
if(message.$id) { this.chatServiceService.getMessageAttachmentByMessageId(message).then((result)=> {
this.chatServiceService.getMessageAttachmentByMessageId(message).then((result)=> { if(result.isOk()) {
if(result.isOk()) { message.attachments[0].safeFile = result.value
message.attachments[0].safeFile = result.value
if(result.value.startsWith('blob:http')) {
message.attachments[0].blobURl = true
} }
}) }
} })
} }
} }
@@ -437,26 +436,34 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
listenToIncomingMessage() { listenToIncomingMessage() {
this.messageReceiveSubject?.unsubscribe(); this.messageReceiveSubject?.unsubscribe();
this.messageReceiveSubject = this.chatServiceService.listenToIncomingMessage(this.roomId).subscribe(async (message) => { this.messageReceiveSubject = this.chatServiceService.listenToIncomingMessage(this.roomId).subscribe(async (_message) => {
const date = whatsappDate(message.sentAt, false) const date = whatsappDate(_message.sentAt, false)
if(!this.date[date]) { if(!this.date[date]) {
this.date[date] = true this.date[date] = true
const Ballon = XBallon(message) const Ballon = XBallon(_message)
this.messages1[this.roomId].push(Ballon) this.messages1[this.roomId].push(Ballon)
} }
const message = new MessageViewModal(_message)
this.messages1[this.roomId].push(new MessageViewModal(message)) this.messages1[this.roomId].push(new MessageViewModal(message))
console.log('message=======', message)
if(message.hasAttachment) { if(message.hasAttachment) {
const result = await this.chatServiceService.downloadMessageAttachmentByMessageId({ const result = await this.chatServiceService.downloadMessageAttachmentByMessageId({
$messageId: message.$id, $messageId: message.id,
id: message.attachments[0].id id: message.attachments[0].id
}) })
if(result.isOk()){ if(result.isOk()) {
message.attachments[0].safeFile = result.value message.attachments[0].safeFile = result.value
if((result.value as unknown as string).startsWith('blob:http')) {
message.attachments[0].blobURl = true
} else {
message.attachments[0].blobURl = false
}
} }
} }
@@ -7,13 +7,15 @@ import { IonicModule } from '@ionic/angular';
import { ViewOncesPageRoutingModule } from './view-onces-routing.module'; import { ViewOncesPageRoutingModule } from './view-onces-routing.module';
import { ViewOncesImagePage } from './view-onces.page'; import { ViewOncesImagePage } from './view-onces.page';
import { PipesModule } from 'src/app/pipes/pipes.module';
@NgModule({ @NgModule({
imports: [ imports: [
CommonModule, CommonModule,
FormsModule, FormsModule,
IonicModule, IonicModule,
ViewOncesPageRoutingModule ViewOncesPageRoutingModule,
PipesModule
], ],
declarations: [ViewOncesImagePage] declarations: [ViewOncesImagePage]
}) })
@@ -11,6 +11,14 @@
<ion-content> <ion-content>
<div class="justify-center align-center d-flex width-100 height-100"> <div class="justify-center align-center d-flex width-100 height-100">
<img [src]="params.imageDataUrl">
<img
*ngIf="blobURl"
[src]="params.imageDataUrl|safehtml"
>
<img
*ngIf="!blobURl"
[src]="params.imageDataUrl"
>
</div> </div>
</ion-content> </ion-content>
@@ -19,19 +19,22 @@ export type ViewOncesImagePageInput = z.infer<typeof ViewOncesImagePageInputSche
export class ViewOncesImagePage implements OnInit { export class ViewOncesImagePage implements OnInit {
params: ViewOncesImagePageInput params: ViewOncesImagePageInput
blobURl: Boolean;
constructor( constructor(
private navParams: NavParams, private navParams: NavParams,
public modalController: ModalController, public modalController: ModalController,
) { ) {
this.params = this.navParams.data this.params = this.navParams.data
} }
ngOnInit() { ngOnInit() {
if(this.params.imageDataUrl.startsWith('blob:http')) {
// console.log('niceddd') this.blobURl = true
// this.message = this.navParams.get('message'); } else {
// console.log('this.message', this.message) this.blobURl = false
}
} }
closePage() { closePage() {
+35 -7
View File
@@ -1,10 +1,38 @@
import { MessageEntity, MessageEntitySchema, IMessageType, IMessage } from "src/app/core/chat/entity/message"; import { MessageEntity, MessageEntitySchema, IMessageType, IMessage, MessageEntityAttachmentSchema } from "src/app/core/chat/entity/message";
import { SessionStore } from "src/app/store/session.service"; import { SessionStore } from "src/app/store/session.service";
import { z } from "zod";
const MessageViewModalSchema = MessageEntitySchema.pick({
$id: true,
canEdit: true,
editedAt: true,
id: true,
info: true,
isDeleted: true,
message: true,
messageType: true,
oneShot: true,
origin: true,
reactions: true,
receiverId: true,
requestId: true,
requireUnlock: true,
roomId: true,
sendAttemp: true,
sender: true,
sending: true,
sentAt: true
}).extend({
attachments: MessageEntityAttachmentSchema.extend({
blobURl: z.boolean()
}).array().optional()
})
export type i = z.infer<typeof MessageViewModalSchema>
export class MessageViewModal { export class MessageViewModal {
$id?: number $id?: string
id?: string id?: string
roomId?: string roomId?: string
receiverId?: number receiverId?: number
@@ -13,15 +41,15 @@ export class MessageViewModal {
oneShot: boolean = false oneShot: boolean = false
sentAt?: string sentAt?: string
requireUnlock: boolean = false requireUnlock: boolean = false
info: typeof MessageEntitySchema._type.info = [] info: typeof MessageViewModalSchema._type.info = []
sender!: typeof MessageEntitySchema._type.sender sender!: typeof MessageViewModalSchema._type.sender
sending: boolean = false sending: boolean = false
sendAttemp = 0 sendAttemp = 0
messageType = IMessageType.normal messageType = IMessageType.normal
attachments: typeof MessageEntitySchema._type.attachments = [] attachments: typeof MessageViewModalSchema._type.attachments = []
reactions: typeof MessageEntitySchema._type.reactions = [] reactions: typeof MessageViewModalSchema._type.reactions = []
requestId: string requestId: string
isDeleted: typeof MessageEntitySchema._type.isDeleted = false isDeleted: typeof MessageViewModalSchema._type.isDeleted = false
status!: 'allViewed' | 'allReceived'| 'enviado'| 'enviar' status!: 'allViewed' | 'allReceived'| 'enviado'| 'enviar'
messageUiType!: 'info-meeting'| 'my-message'| 'other-message' messageUiType!: 'info-meeting'| 'my-message'| 'other-message'
+53
View File
@@ -0,0 +1,53 @@
import { Injectable } from '@angular/core';
import { MessageViewModal } from './model/message';
import { MessageLocalDataSourceService } from 'src/app/module/chat/data/repository/message/message-local-data-source.service';
import { whatsappDate } from '../../shared/utils/whatappdate';
import { XBallon } from '../utils/messageBallon';
@Injectable({
providedIn: 'root'
})
export class RoomStore {
roomId: string;
date: {[key: string]: Object} = {}
constructor(
private messageLocalDataSourceService: MessageLocalDataSourceService,
) {}
openRoom() {
}
messages1: {[key: string]: MessageViewModal[]} = {}
async getMessages() {
// dont remove this line
this.messages1[this.roomId] = []
let messages = await this.messageLocalDataSourceService.getItems(this.roomId)
this.messages1[this.roomId] = []
this.date = {}
const allMessage = [];
console.time("mappingTime");
for(const message of messages) {
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
this.date[date] = true
const Ballon = XBallon(message)
allMessage.push(Ballon)
}
allMessage.push(new MessageViewModal(message))
}
console.timeEnd("mappingTime");
this.messages1[this.roomId] = allMessage
// if(messages.length >= 1) {
// this.messages1[this.roomId].push(LastMessage)
// }
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { IMessageType } from "src/app/core/chat/entity/message";
export function XBallon(message: any) { export function XBallon(message: any) {
const MessageBallon = new MessageViewModal(message as any) const MessageBallon = new MessageViewModal(message as any)
MessageBallon.$id = 0 MessageBallon.$id = ''
MessageBallon.id = '' MessageBallon.id = ''
MessageBallon.isDeleted = false MessageBallon.isDeleted = false
MessageBallon.sentAt = message.sentAt MessageBallon.sentAt = message.sentAt