Skip to content

Commit

Permalink
testing
Browse files Browse the repository at this point in the history
  • Loading branch information
JAYBORICHA07 committed Nov 25, 2023
1 parent 39161e7 commit 35a02e9
Show file tree
Hide file tree
Showing 5 changed files with 199 additions and 15 deletions.
64 changes: 64 additions & 0 deletions src/controller/chatController.ts
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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 ()=>{
Expand Down
101 changes: 101 additions & 0 deletions src/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -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])
}
28 changes: 28 additions & 0 deletions src/router/chat.ts
Original file line number Diff line number Diff line change
@@ -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;
19 changes: 4 additions & 15 deletions src/wa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 35a02e9

Please sign in to comment.