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
}
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({
$id: z.any().optional(),
id: z.string().uuid().optional(),
@@ -50,18 +63,7 @@ export const MessageEntitySchema = z.object({
deliverAt: z.string().nullable()
})).optional(),
sending: z.boolean().optional(),
attachments: z.array(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()
})).optional(),
attachments: z.array(MessageEntityAttachmentSchema).optional(),
origin: z.enum(['history', 'local', 'incoming']).optional(),
requestId: z.string().optional(),
sendAttemp: z.number().optional(),
@@ -7,11 +7,11 @@ export const AttachmentTableSchema = z.object({
$id: z.number().optional(), // local id
$messageId: z.string(),
attachmentId: z.string().optional(),
file: z.instanceof(Blob),
file: z.instanceof(Blob).optional(),
base64: zodDataUrlSchema.nullable().optional(),
//
fileType: z.nativeEnum(MessageAttachmentFileType),
source: z.nativeEnum(MessageAttachmentSource),
fileType: z.nativeEnum(MessageAttachmentFileType).optional(),
source: z.nativeEnum(MessageAttachmentSource).optional(),
fileName: z.string().optional(),
applicationId: z.number().optional(),
docId: z.string().optional(),
@@ -49,5 +49,5 @@ export const MessageTableSchema = z.object({
export type MessageTable = z.infer<typeof MessageTableSchema>
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 { ZodError} from 'zod';
import { IDBError } from './types';
import Dexie, { EntityTable, Table } from 'Dexie';
// Define a type for the Result of repository operations
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 insertMany(documents: T[]): Promise<RepositoryResult<number[], T[]>>
@@ -1,5 +1,5 @@
import { Result, ok, err } from 'neverthrow';
import { EntityTable } from 'Dexie';
import Dexie, { EntityTable, Table } from 'Dexie';
import { ZodError, ZodObject, ZodSchema } from 'zod';
import { Logger } from 'src/app/services/logger/main/service';
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 ZodSchema: 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.ZodSchema = ZodSchema
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>> {
const dataValidation = this.ZodSchema.safeParse(document)
@@ -3,7 +3,7 @@ import { liveQuery } from 'Dexie';
import { MessageEntity } from '../../../../../core/chat/entity/message';
import { DexieRepository } from 'src/app/infra/repository/dexie/dexie-repository.service';
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 { IMessageLocalRepository } from 'src/app/core/chat/repository/message/message-local-repository';
import { BehaviorSubject, combineLatest, from, Observable } from 'rxjs';
@@ -13,13 +13,13 @@ import { v4 as uuidv4 } from 'uuid'
@Injectable({
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 lastTimestamp = 0;
constructor() {
super(chatDatabase.message, MessageTableSchema)
super(chatDatabase.message, MessageTableSchema, chatDatabase)
this.setAllSenderToFalse();
this.onCreatingHook()
@@ -54,22 +54,33 @@ export class MessageLocalDataSourceService extends DexieRepository<MessageTable,
}
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 {
await chatDatabase.transaction('rw', chatDatabase.message, async () => {
// Perform the update operation within the transaction
await chatDatabase.message.toCollection().modify({ sending: false });
});
// console.log('All messages updated successfully.');
} catch (error) {
console.error('Error updating messages:', error);
}
}
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[]> {
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 () {
@@ -4,6 +4,8 @@ import { Logger } from 'src/app/services/logger/main/service';
import { convertBlobToDataURL, createBlobUrl } from 'src/app/utils/ToBase64';
import { AttachmentLocalDataSource } from 'src/app/module/chat/data/repository/attachment/attachment-local-repository.service'
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({
$messageId: z.string(),
@@ -24,28 +26,43 @@ export class DownloadMessageAttachmentUserCaseService {
) { }
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', {
// data: dataUrl.slice(0, 100)+'...',
context: 'DownloadMessageAttachmentUserCaseService'
})
const result = await this.AttachmentRemoteDataSourceService.getAttachment(input.id)
return result.asyncMap(async (blob) => {
this.AttachmentLocalDataSource.insert({
$messageId: input.$messageId,
id: input.id,
file: blob
})
const dataUrl = await createBlobUrl(blob)
return dataUrl
} else {
if(dataUrl.isOk()) {
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
}
}
})
}
}
@@ -49,7 +49,7 @@ export class SocketMessageUpdateUseCaseService {
messageToSave.sending = false
if(result.isOk() && result.value) {
tracing?.addEvent("Message found")
const updateResult = await this.messageLocalDataSourceService.update(result.value.$id, messageToSave)
tracing.setAttribute('outcome', 'success')
@@ -72,10 +72,16 @@
</div>
<div *ngIf="attachment.fileType == MessageAttachmentFileType.Image">
<img
*ngIf="message.oneShot != true && attachment.blobURl != true"
[src]="attachment.safeFile"
(load)="onImageLoad(message, messageIndex)"
(error)="onImageError()"
>
<img
*ngIf="message.oneShot != true"
[src]="attachment.safeFile"
*ngIf="message.oneShot != true && attachment.blobURl"
[src]="attachment.safeFile|safehtml"
(load)="onImageLoad(message, messageIndex)"
(error)="onImageError()"
>
@@ -320,10 +320,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
// }
// return true; // Keep messages without an id
// });
messages = messages.sort((a: any, b: any) => a.$createAt - b.$createAt)
console.time("mappingTime");
for(const message of messages) {
const date = whatsappDate(message.sentAt, false)
if(!this.date[date]) {
@@ -334,12 +331,12 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
allMessage.push(new MessageViewModal(message))
}
console.timeEnd("mappingTime");
console.time("mappingTime");
this.messages1[this.roomId] = allMessage
console.timeEnd("mappingTime");
// if(messages.length >= 1) {
// 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]) {
if(message.hasAttachment && message.attachments[0].source != MessageAttachmentSource.Webtrix) {
if(message.$id) {
this.chatServiceService.getMessageAttachmentByMessageId(message).then((result)=> {
if(result.isOk()) {
message.attachments[0].safeFile = result.value
this.chatServiceService.getMessageAttachmentByMessageId(message).then((result)=> {
if(result.isOk()) {
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() {
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]) {
this.date[date] = true
const Ballon = XBallon(message)
const Ballon = XBallon(_message)
this.messages1[this.roomId].push(Ballon)
}
const message = new MessageViewModal(_message)
this.messages1[this.roomId].push(new MessageViewModal(message))
console.log('message=======', message)
if(message.hasAttachment) {
const result = await this.chatServiceService.downloadMessageAttachmentByMessageId({
$messageId: message.$id,
$messageId: message.id,
id: message.attachments[0].id
})
if(result.isOk()){
if(result.isOk()) {
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 { ViewOncesImagePage } from './view-onces.page';
import { PipesModule } from 'src/app/pipes/pipes.module';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ViewOncesPageRoutingModule
ViewOncesPageRoutingModule,
PipesModule
],
declarations: [ViewOncesImagePage]
})
@@ -11,6 +11,14 @@
<ion-content>
<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>
</ion-content>
@@ -19,19 +19,22 @@ export type ViewOncesImagePageInput = z.infer<typeof ViewOncesImagePageInputSche
export class ViewOncesImagePage implements OnInit {
params: ViewOncesImagePageInput
blobURl: Boolean;
constructor(
private navParams: NavParams,
public modalController: ModalController,
) {
) {
this.params = this.navParams.data
}
ngOnInit() {
// console.log('niceddd')
// this.message = this.navParams.get('message');
// console.log('this.message', this.message)
if(this.params.imageDataUrl.startsWith('blob:http')) {
this.blobURl = true
} else {
this.blobURl = false
}
}
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 { 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 {
$id?: number
$id?: string
id?: string
roomId?: string
receiverId?: number
@@ -13,15 +41,15 @@ export class MessageViewModal {
oneShot: boolean = false
sentAt?: string
requireUnlock: boolean = false
info: typeof MessageEntitySchema._type.info = []
sender!: typeof MessageEntitySchema._type.sender
info: typeof MessageViewModalSchema._type.info = []
sender!: typeof MessageViewModalSchema._type.sender
sending: boolean = false
sendAttemp = 0
messageType = IMessageType.normal
attachments: typeof MessageEntitySchema._type.attachments = []
reactions: typeof MessageEntitySchema._type.reactions = []
attachments: typeof MessageViewModalSchema._type.attachments = []
reactions: typeof MessageViewModalSchema._type.reactions = []
requestId: string
isDeleted: typeof MessageEntitySchema._type.isDeleted = false
isDeleted: typeof MessageViewModalSchema._type.isDeleted = false
status!: 'allViewed' | 'allReceived'| 'enviado'| 'enviar'
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) {
const MessageBallon = new MessageViewModal(message as any)
MessageBallon.$id = 0
MessageBallon.$id = ''
MessageBallon.id = ''
MessageBallon.isDeleted = false
MessageBallon.sentAt = message.sentAt