From 35a02e90c34851e9ebe9533ff93db1ab47e53c97 Mon Sep 17 00:00:00 2001 From: JAYBORICHA Date: Sat, 25 Nov 2023 19:59:00 +0530 Subject: [PATCH] testing --- src/controller/chatController.ts | 64 ++++++++++++++++++++ src/index.ts | 2 + src/prisma/schema.prisma | 101 +++++++++++++++++++++++++++++++ src/router/chat.ts | 28 +++++++++ src/wa.ts | 19 ++---- 5 files changed, 199 insertions(+), 15 deletions(-) create mode 100644 src/controller/chatController.ts create mode 100644 src/router/chat.ts diff --git a/src/controller/chatController.ts b/src/controller/chatController.ts new file mode 100644 index 0000000..5ade48d --- /dev/null +++ b/src/controller/chatController.ts @@ -0,0 +1,64 @@ +import { serializePrisma } from '../store/utils'; +import type { Request, Response } from 'express'; +import { logger, prisma } from '../shared'; + +const chatController = { + list: async (req: Request, res : Response) => { + try { + // console.log(req.query) + const sessionId:any = req.query.sessionId; + // console.log("sessionId = " + sessionId); + const { cursor = undefined, limit = 25 } = req.query; + // console.log("cursor : "+ cursor+ " limit = " + limit) + const chats = ( + await prisma.chat.findMany({ + cursor: cursor ? { pkId: Number(cursor) } : undefined, + take: Number(limit), + skip: cursor ? 1 : 0, + where: { sessionId }, + }) + ).map((c : any) => serializePrisma(c)); + + // console.log(chats); + + res.status(200).json({ + data: chats, + cursor: + chats.length !== 0 && chats.length === Number(limit) ? chats[chats.length - 1].pkId : null, + }); + } catch (e) { + const message = 'An error occured during chat list'; + logger.error(e, message); + res.status(500).json({ error: message }); + } + }, + find: async (req :Request, res : Response ) => { + try { + const { sessionId, jid } = req.params; + const { cursor = undefined, limit = 25 } = req.query; + const messages = ( + await prisma.message.findMany({ + cursor: cursor ? { pkId: Number(cursor) } : undefined, + take: Number(limit), + skip: cursor ? 1 : 0, + where: { sessionId, remoteJid: jid }, + orderBy: { messageTimestamp: 'desc' }, + }) + ).map((m : any) => serializePrisma(m)); + + res.status(200).json({ + data: messages, + cursor: + messages.length !== 0 && messages.length === Number(limit) + ? messages[messages.length - 1].pkId + : null, + }); + } catch (e) { + const message = 'An error occured during chat find'; + logger.error(e, message); + res.status(500).json({ error: message }); + } + }, +} + +export default chatController; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 2062904..4453e70 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ import bodyParser from 'body-parser'; import sessionRouter from './router/session'; import { logger, prisma } from './shared'; import messageRoutes from './router/message'; +import chatRoutes from './router/chat'; import { init } from './wa'; import { authMiddleware } from './middleware/auth-middleware'; @@ -13,6 +14,7 @@ app.use(bodyParser.json()); app.use(authMiddleware) app.use('/session',sessionRouter); app.use('/messages',messageRoutes); +app.use('/chats',chatRoutes) app.all('*',(req,res) => res.status(400).json({error: 'Wrong Url'})); (async ()=>{ diff --git a/src/prisma/schema.prisma b/src/prisma/schema.prisma index 4eb13ed..242d9c6 100644 --- a/src/prisma/schema.prisma +++ b/src/prisma/schema.prisma @@ -20,3 +20,104 @@ model Session { @@unique([sessionId, id], map: "unique_id_per_session_id") @@index([sessionId]) } + +model Chat { + pkId Int @id @default(autoincrement()) + sessionId String @db.VarChar(128) + archived Boolean? + contactPrimaryIdentityKey Bytes? + conversationTimestamp BigInt? + createdAt BigInt? + createdBy String? @db.VarChar(128) + description String? @db.VarChar(255) + disappearingMode Json? + displayName String? @db.VarChar(128) + endOfHistoryTransfer Boolean? + endOfHistoryTransferType Int? + ephemeralExpiration Int? + ephemeralSettingTimestamp BigInt? + id String @db.VarChar(128) + isDefaultSubgroup Boolean? + isParentGroup Boolean? + lastMsgTimestamp BigInt? + lidJid String? @db.VarChar(128) + markedAsUnread Boolean? + mediaVisibility Int? + messages Json? + muteEndTime BigInt? + name String? @db.VarChar(128) + newJid String? @db.VarChar(128) + notSpam Boolean? + oldJid String? @db.VarChar(128) + pHash String? @db.VarChar(128) + parentGroupId String? @db.VarChar(128) + participant Json? + pinned Int? + pnJid String? @db.VarChar(128) + pnhDuplicateLidThread Boolean? + readOnly Boolean? + shareOwnPn Boolean? + support Boolean? + suspended Boolean? + tcToken Bytes? + tcTokenSenderTimestamp BigInt? + tcTokenTimestamp BigInt? + terminated Boolean? + unreadCount Int? + unreadMentionCount Int? + wallpaper Json? + lastMessageRecvTimestamp Int? +} + +model Message { + pkId Int @id @default(autoincrement()) + sessionId String @db.VarChar(128) + remoteJid String @db.VarChar(128) + id String @db.VarChar(128) + agentId String? @db.VarChar(128) + bizPrivacyStatus Int? + broadcast Boolean? + clearMedia Boolean? + duration Int? + ephemeralDuration Int? + ephemeralOffToOn Boolean? + ephemeralOutOfSync Boolean? + ephemeralStartTimestamp BigInt? + finalLiveLocation Json? + futureproofData Bytes? + ignore Boolean? + keepInChat Json? + key Json + labels Json? + mediaCiphertextSha256 Bytes? + mediaData Json? + message Json? + messageC2STimestamp BigInt? + messageSecret Bytes? + messageStubParameters Json? + messageStubType Int? + messageTimestamp BigInt? + multicast Boolean? + originalSelfAuthorUserJidString String? @db.VarChar(128) + participant String? @db.VarChar(128) + paymentInfo Json? + photoChange Json? + pollAdditionalMetadata Json? + pollUpdates Json? + pushName String? @db.VarChar(128) + quotedPaymentInfo Json? + quotedStickerData Json? + reactions Json? + revokeMessageTimestamp BigInt? + starred Boolean? + status Int? + statusAlreadyViewed Boolean? + statusPsa Json? + urlNumber Boolean? + urlText Boolean? + userReceipt Json? + verifiedBizName String? @db.VarChar(128) + + @@unique([sessionId, remoteJid, id], map: "unique_message_key_per_session_id") + @@index([sessionId]) +} \ No newline at end of file diff --git a/src/router/chat.ts b/src/router/chat.ts new file mode 100644 index 0000000..598f047 --- /dev/null +++ b/src/router/chat.ts @@ -0,0 +1,28 @@ +import { Router } from "express" +import { body, query } from "express-validator" +import requestValidator from "../middleware/requestValidator" +import validateSession from "../middleware/validateSession" +import chatController from "../controller/chatController" + +const chatRoutes = Router(); + +chatRoutes.get( + '/chat', + query('cursor').isNumeric().optional(), + query('limit').isNumeric().optional(), + query('sessionId').isString().notEmpty(), + requestValidator, + chatController.list +) + +chatRoutes.get( + ':jid', + query('cursor').isNumeric().optional(), + query('limit').isNumeric().optional(), + query('sessionId').isString().notEmpty(), + requestValidator, + chatController.find +) + + +export default chatRoutes; \ No newline at end of file diff --git a/src/wa.ts b/src/wa.ts index 4b03b0f..677cfd2 100644 --- a/src/wa.ts +++ b/src/wa.ts @@ -185,23 +185,12 @@ export async function createSession(options:createSessionOptions) { } // credentials updated -- save them - if(events['creds.update']) { - await saveCreds() - } - // sample reply msg to see if it is working or not - // if(events['messages.upsert']) { - // const upsert = events['messages.upsert'] - // console.log('recv messages ', JSON.stringify(upsert, undefined, 2)) - - // if(upsert.type === 'notify') { - // for(const msg of upsert.messages) { - // console.log('replying to', msg.key.remoteJid) - // await sock!.readMessages([msg.key]) - // await sendMessageWTyping({ text: 'Hello there!' }, msg.key.remoteJid!) - // } - // } + // if(events['creds.update']) { + // await saveCreds() // } + // sample reply msg to see if it is working or not + }) return sock;