Skip to content

Commit 001094a

Browse files
authoredOct 25, 2023
Merge branch 'code-chat-br:main' into main
2 parents d0d7f10 + 8b100a6 commit 001094a

10 files changed

+156
-85
lines changed
 

‎package.json

+18-18
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "whatsapp-api",
3-
"version": "1.2.7",
3+
"version": "1.2.8",
44
"description": "Rest api for communication with WhatsApp",
55
"main": "./dist/src/main.js",
66
"scripts": {
@@ -45,7 +45,7 @@
4545
"@hapi/boom": "^10.0.1",
4646
"@whiskeysockets/baileys": "^6.4.0",
4747
"axios": "^1.3.5",
48-
"class-validator": "^0.13.2",
48+
"class-validator": "^0.14.0",
4949
"compression": "^1.7.4",
5050
"cors": "^2.8.5",
5151
"cross-env": "^7.0.3",
@@ -55,17 +55,17 @@
5555
"express-async-errors": "^3.1.1",
5656
"express-session": "^1.17.3",
5757
"hbs": "^4.2.0",
58-
"jimp": "^0.16.13",
58+
"jimp": "^0.22.10",
5959
"join": "^3.0.0",
6060
"js-yaml": "^4.1.0",
6161
"jsonschema": "^1.4.1",
62-
"jsonwebtoken": "^8.5.1",
62+
"jsonwebtoken": "^9.0.2",
6363
"mime-types": "^2.1.35",
64-
"mongoose": "^6.10.5",
64+
"mongoose": "^7.6.2",
6565
"multer": "^1.4.5-lts.1",
6666
"node-cache": "^5.1.2",
6767
"node-mime-types": "^1.1.0",
68-
"pino": "^8.11.0",
68+
"pino": "^8.16.0",
6969
"qrcode": "^1.5.1",
7070
"qrcode-terminal": "^0.12.0",
7171
"redis": "^4.6.5",
@@ -76,26 +76,26 @@
7676
"devDependencies": {
7777
"@types/compression": "^1.7.2",
7878
"@types/cors": "^2.8.13",
79-
"@types/express": "^4.17.17",
79+
"@types/express": "^4.17.19",
8080
"@types/express-session": "^1.17.7",
81-
"@types/js-yaml": "^4.0.5",
82-
"@types/jsonwebtoken": "^8.5.9",
81+
"@types/js-yaml": "^4.0.7",
82+
"@types/jsonwebtoken": "^9.0.3",
8383
"@types/mime-types": "^2.1.2",
8484
"@types/multer": "^1.4.7",
85-
"@types/node": "^18.15.11",
85+
"@types/node": "^20.8.6",
8686
"@types/qrcode": "^1.5.0",
8787
"@types/qrcode-terminal": "^0.12.0",
8888
"@types/swagger-ui-express": "^4.1.3",
89-
"@types/uuid": "^8.3.4",
89+
"@types/uuid": "^9.0.5",
9090
"@types/yamljs": "^0.2.31",
91-
"@typescript-eslint/eslint-plugin": "^5.57.1",
92-
"@typescript-eslint/parser": "^5.57.1",
91+
"@typescript-eslint/eslint-plugin": "^6.7.5",
92+
"@typescript-eslint/parser": "^6.7.5",
9393
"copy-webpack-plugin": "^11.0.0",
94-
"eslint": "^8.38.0",
95-
"eslint-config-prettier": "^8.8.0",
96-
"eslint-plugin-prettier": "^4.2.1",
97-
"prettier": "^2.8.7",
94+
"eslint": "^8.51.0",
95+
"eslint-config-prettier": "^9.0.0",
96+
"eslint-plugin-prettier": "^5.0.1",
97+
"prettier": "^3.0.3",
9898
"ts-node-dev": "^2.0.0",
99-
"typescript": "^4.9.5"
99+
"typescript": "^5.2.2"
100100
}
101101
}

‎src/db/db.connect.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ export const dbserver = (() => {
4646
});
4747
logger.info('ON - dbName: ' + dbs['$dbName']);
4848
process.on('beforeExit', () => {
49-
dbserver.destroy(true, (error) => logger.error(error));
49+
dbserver.destroy(true);
5050
});
5151

5252
return dbs;

‎src/docs/swagger.yaml

+27
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,33 @@ paths:
193193
base64:
194194
type: string
195195
description: The QR Code as a string.
196+
/instance/reload/{instanceName}:
197+
get:
198+
tags:
199+
- Instance Controller
200+
summary: Instance Reload
201+
parameters:
202+
- name: instanceName
203+
in: path
204+
required: true
205+
schema:
206+
type: string
207+
description: Reload to your instance.
208+
example: 'codechat'
209+
responses:
210+
'200':
211+
description: Successful response
212+
content:
213+
application/json:
214+
schema:
215+
type: object
216+
properties:
217+
instance:
218+
type: string
219+
state:
220+
type: string
221+
statusReason:
222+
type: string
196223
/instance/connectionState/{instanceName}:
197224
get:
198225
tags:

‎src/utils/use-multi-file-auth-state-db.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export async function useMultiFileAuthStateDb(coll: string): Promise<AuthState>
5858
try {
5959
await client.connect();
6060
return await collection.replaceOne(
61-
{ _id: key },
61+
{ _id: key } as any,
6262
JSON.parse(JSON.stringify(data, BufferJSON.replacer)),
6363
{ upsert: true },
6464
);
@@ -68,7 +68,7 @@ export async function useMultiFileAuthStateDb(coll: string): Promise<AuthState>
6868
const readData = async (key: string): Promise<any> => {
6969
try {
7070
await client.connect();
71-
const data = await collection.findOne({ _id: key });
71+
const data = await collection.findOne({ _id: key } as any);
7272
const creds = JSON.stringify(data);
7373
return JSON.parse(creds, BufferJSON.reviver);
7474
} catch {}
@@ -77,7 +77,7 @@ export async function useMultiFileAuthStateDb(coll: string): Promise<AuthState>
7777
const removeData = async (key: string) => {
7878
try {
7979
await client.connect();
80-
return await collection.deleteOne({ _id: key });
80+
return await collection.deleteOne({ _id: key } as any);
8181
} catch {}
8282
};
8383

‎src/whatsapp/controllers/instance.controller.ts

+18
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,24 @@ export class InstanceController {
9696
}
9797
}
9898

99+
public async reloadConnection({ instanceName }: InstanceDto) {
100+
try {
101+
const instance = this.waMonitor.waInstances[instanceName];
102+
const state = instance?.connectionStatus?.state;
103+
104+
switch (state) {
105+
case 'open':
106+
await instance.reloadConnection();
107+
await delay(2000);
108+
return await this.connectionState({ instanceName });
109+
default:
110+
return await this.connectionState({ instanceName });
111+
}
112+
} catch (error) {
113+
this.logger.error(error);
114+
}
115+
}
116+
99117
public async connectToWhatsapp({ instanceName }: InstanceDto) {
100118
try {
101119
const instance = this.waMonitor.waInstances[instanceName];

‎src/whatsapp/models/message.model.ts

+3
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ class Key {
5353
}
5454

5555
export class MessageRaw {
56+
constructor(props?: MessageRaw) {
57+
Object.assign(this, props);
58+
}
5659
_id?: string;
5760
key?: Key;
5861
pushName?: string;

‎src/whatsapp/routers/instance.router.ts

+10
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,16 @@ export class InstanceRouter extends RouterBroker {
8888

8989
return res.status(HttpStatus.OK).json(response);
9090
})
91+
.get(this.routerPath('reload'), ...guards, async (req, res) => {
92+
const response = await this.dataValidate<InstanceDto>({
93+
request: req,
94+
schema: instanceNameSchema,
95+
ClassRef: InstanceDto,
96+
execute: (instance) => instanceController.reloadConnection(instance),
97+
});
98+
99+
return res.status(HttpStatus.OK).json(response);
100+
})
91101
.delete(this.routerPath('logout'), ...guards, async (req, res) => {
92102
const response = await this.dataValidate<InstanceDto>({
93103
request: req,

‎src/whatsapp/services/monitor.service.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ export class WAMonitoringService {
122122
$or: [
123123
{ _id: { $regex: /^app.state.*/ } },
124124
{ _id: { $regex: /^session-.*/ } },
125-
],
125+
] as any[],
126126
});
127127
});
128128
} else if (this.redis.ENABLED) {
@@ -235,7 +235,7 @@ export class WAMonitoringService {
235235
private noConnection() {
236236
this.eventEmitter.on('no.connection', async (instanceName) => {
237237
const del = this.configService.get<DelInstance>('DEL_INSTANCE');
238-
if(del) {
238+
if (del) {
239239
try {
240240
this.waInstances[instanceName] = undefined;
241241
this.cleaningUp(instanceName);

‎src/whatsapp/services/whatsapp.service.ts

+73-57
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ export class WAStartupService {
190190
'-instances',
191191
)
192192
.collection(this.instanceName);
193-
const data = await collection.findOne({ _id: 'creds' });
193+
const data = await collection.findOne({ _id: 'creds' } as any);
194194
if (data) {
195195
const creds = JSON.parse(JSON.stringify(data), BufferJSON.reviver);
196196
profileName = creds.me?.name || creds.me?.verifiedName;
@@ -444,43 +444,55 @@ export class WAStartupService {
444444
return await useMultiFileAuthState(join(INSTANCE_DIR, this.instance.name));
445445
}
446446

447-
public async connectToWhatsapp(): Promise<WASocket> {
448-
try {
449-
this.loadWebhook();
447+
private async setSocket() {
448+
this.endSession = false;
450449

451-
this.instance.authState = await this.defineAuthState();
450+
this.instance.authState = await this.defineAuthState();
452451

453-
const { version } = await fetchLatestBaileysVersion();
454-
const session = this.configService.get<ConfigSessionPhone>('CONFIG_SESSION_PHONE');
455-
const browser: WABrowserDescription = [session.CLIENT, session.NAME, release()];
452+
const { version } = await fetchLatestBaileysVersion();
453+
const session = this.configService.get<ConfigSessionPhone>('CONFIG_SESSION_PHONE');
454+
const browser: WABrowserDescription = [session.CLIENT, session.NAME, release()];
456455

457-
const socketConfig: UserFacingSocketConfig = {
458-
auth: {
459-
creds: this.instance.authState.state.creds,
460-
keys: makeCacheableSignalKeyStore(
461-
this.instance.authState.state.keys,
462-
P({ level: 'error' }),
463-
),
464-
},
465-
logger: P({ level: 'error' }),
466-
printQRInTerminal: false,
467-
browser,
468-
version,
469-
connectTimeoutMs: 60_000,
470-
qrTimeout: 40_000,
471-
emitOwnEvents: false,
472-
msgRetryCounterCache: this.msgRetryCounterCache,
473-
getMessage: this.getMessage as any,
474-
generateHighQualityLinkPreview: true,
475-
syncFullHistory: true,
476-
userDevicesCache: this.userDevicesCache,
477-
transactionOpts: { maxCommitRetries: 3, delayBetweenTriesMs: 10 },
478-
};
456+
const socketConfig: UserFacingSocketConfig = {
457+
auth: {
458+
creds: this.instance.authState.state.creds,
459+
keys: makeCacheableSignalKeyStore(
460+
this.instance.authState.state.keys,
461+
P({ level: 'silent' }) as any,
462+
),
463+
},
464+
logger: P({ level: 'silent' }) as any,
465+
printQRInTerminal: false,
466+
browser,
467+
version,
468+
connectTimeoutMs: 60_000,
469+
qrTimeout: 10_000,
470+
emitOwnEvents: false,
471+
msgRetryCounterCache: this.msgRetryCounterCache,
472+
getMessage: this.getMessage as any,
473+
generateHighQualityLinkPreview: true,
474+
syncFullHistory: true,
475+
userDevicesCache: this.userDevicesCache,
476+
transactionOpts: { maxCommitRetries: 1, delayBetweenTriesMs: 10 },
477+
};
479478

480-
this.endSession = false;
479+
return makeWASocket(socketConfig);
480+
}
481481

482-
this.client = makeWASocket(socketConfig);
482+
public async reloadConnection(): Promise<WASocket> {
483+
try {
484+
this.client = await this.setSocket();
485+
return this.client;
486+
} catch (error) {
487+
this.logger.error(error);
488+
throw new InternalServerErrorException(error?.toString());
489+
}
490+
}
483491

492+
public async connectToWhatsapp(): Promise<WASocket> {
493+
try {
494+
this.loadWebhook();
495+
this.client = await this.setSocket();
484496
this.eventHandler();
485497

486498
return this.client;
@@ -649,35 +661,39 @@ export class WAStartupService {
649661
},
650662
database: Database,
651663
) => {
652-
const received = messages[0];
653-
if (
654-
type !== 'notify' ||
655-
!received?.message ||
656-
received.message?.protocolMessage ||
657-
received.message.senderKeyDistributionMessage
658-
) {
659-
return;
660-
}
664+
for (const received of messages) {
665+
if (
666+
type !== 'notify' ||
667+
!received?.message ||
668+
received.message?.protocolMessage ||
669+
received.message.senderKeyDistributionMessage
670+
) {
671+
return;
672+
}
661673

662-
this.client.sendPresenceUpdate('unavailable');
674+
this.client.sendPresenceUpdate('unavailable');
663675

664-
if (Long.isLong(received.messageTimestamp)) {
665-
received.messageTimestamp = received.messageTimestamp?.toNumber();
666-
}
676+
if (Long.isLong(received.messageTimestamp)) {
677+
received.messageTimestamp = received.messageTimestamp?.toNumber();
678+
}
667679

668-
const messageRaw: MessageRaw = {
669-
key: received.key,
670-
pushName: received.pushName,
671-
message: { ...received.message },
672-
messageTimestamp: received.messageTimestamp as number,
673-
owner: this.instance.wuid,
674-
source: getDevice(received.key.id),
675-
};
680+
const messageRaw = new MessageRaw({
681+
key: received.key,
682+
pushName: received.pushName,
683+
message: { ...received.message },
684+
messageTimestamp: received.messageTimestamp as number,
685+
owner: this.instance.wuid,
686+
source: getDevice(received.key.id),
687+
});
676688

677-
this.logger.log(received);
689+
this.logger.log(received);
678690

679-
await this.repository.message.insert([messageRaw], database.SAVE_DATA.NEW_MESSAGE);
680-
await this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
691+
await this.repository.message.insert(
692+
[messageRaw],
693+
database.SAVE_DATA.NEW_MESSAGE,
694+
);
695+
await this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
696+
}
681697
},
682698

683699
'messages.update': async (args: WAMessageUpdate[], database: Database) => {
@@ -1234,7 +1250,7 @@ export class WAStartupService {
12341250
'buffer',
12351251
{},
12361252
{
1237-
logger: P({ level: 'error' }),
1253+
logger: P({ level: 'silent' }) as any,
12381254
reuploadRequest: this.client.updateMediaMessage,
12391255
},
12401256
);

0 commit comments

Comments
 (0)