-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathinstance.controller.ts
247 lines (224 loc) · 10.2 KB
/
instance.controller.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/**
* ┌──────────────────────────────────────────────────────────────────────────────┐
* │ @author jrCleber │
* │ @filename instance.controller.ts │
* │ Developed by: Cleber Wilson │
* │ Creation date: Jul 17, 2022 │
* │ Contact: contato@codechat.dev │
* ├──────────────────────────────────────────────────────────────────────────────┤
* │ @copyright © Cleber Wilson 2022. All rights reserved. │
* │ Licensed under the Apache License, Version 2.0 │
* │ │
* │ @license "https://github.com/code-chat-br/whatsapp-api/blob/main/LICENSE" │
* │ │
* │ You may not use this file except in compliance with the License. │
* │ You may obtain a copy of the License at │
* │ │
* │ http://www.apache.org/licenses/LICENSE-2.0 │
* │ │
* │ Unless required by applicable law or agreed to in writing, software │
* │ distributed under the License is distributed on an "AS IS" BASIS, │
* │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
* │ │
* │ See the License for the specific language governing permissions and │
* │ limitations under the License. │
* │ │
* │ @class │
* │ @constructs InstanceController │
* │ @param {WAMonitoringService} waMonit │
* │ @param {ConfigService} configService │
* │ @param {RepositoryBroker} repository │
* │ @param {EventEmitter2} eventEmitter │
* │ @param {AuthService} authService │
* ├──────────────────────────────────────────────────────────────────────────────┤
* │ @important │
* │ For any future changes to the code in this file, it is recommended to │
* │ contain, together with the modification, the information of the developer │
* │ who changed it and the date of modification. │
* └──────────────────────────────────────────────────────────────────────────────┘
*/
import { delay } from '@whiskeysockets/baileys';
import EventEmitter2 from 'eventemitter2';
import { ConfigService } from '../../config/env.config';
import {
BadRequestException,
InternalServerErrorException,
NotFoundException,
} from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { WAMonitoringService } from '../services/monitor.service';
import { Logger } from '../../config/logger.config';
import { Request } from 'express';
import { Repository } from '../../repository/repository.service';
import { InstanceService, OldToken } from '../services/instance.service';
import { WAStartupService } from '../services/whatsapp.service';
import { isString } from 'class-validator';
import { ProviderFiles } from '../../provider/sessions';
import { Websocket } from '../../websocket/server';
export class InstanceController {
constructor(
private readonly waMonitor: WAMonitoringService,
private readonly configService: ConfigService,
private readonly repository: Repository,
private readonly eventEmitter: EventEmitter2,
private readonly instanceService: InstanceService,
private readonly providerFiles: ProviderFiles,
private readonly ws: Websocket,
) {}
private readonly logger = new Logger(this.configService, InstanceController.name);
public async createInstance(instance: InstanceDto, req: Request) {
const created = await this.instanceService.createInstance(instance);
try {
req.session[instance.instanceName] = Buffer.from(
JSON.stringify(created.Auth),
).toString('base64');
return created;
} catch (error) {
throw new InternalServerErrorException(error?.message);
}
}
public async reloadConnection({ instanceName }: InstanceDto) {
try {
const instance = this.waMonitor.waInstances[instanceName];
const state = instance?.connectionStatus?.state;
switch (state) {
case 'open':
await instance.reloadConnection();
await delay(2000);
return await this.connectionState({ instanceName });
default:
return await this.connectionState({ instanceName });
}
} catch (error) {
this.logger.error(error);
}
}
public async connectToWhatsapp({ instanceName }: InstanceDto) {
const find = await this.repository.instance.findUnique({
where: { name: instanceName },
});
if (!find) {
throw new NotFoundException('Instance not found');
}
try {
let instance: WAStartupService;
instance = this.waMonitor.waInstances.get(instanceName);
const info = instance?.getInstance();
if (info?.status.state === 'open') {
throw new Error('Instance already connected');
}
const state = info?.status.state || 'close';
if (!instance || !info?.status || info?.status?.state === 'refused') {
instance = new WAStartupService(
this.configService,
this.eventEmitter,
this.repository,
this.providerFiles,
this.ws,
);
await instance.setInstanceName(instanceName);
this.waMonitor.addInstance(instanceName, instance);
}
switch (state) {
case 'close':
await instance.connectToWhatsapp();
await delay(3000);
return instance.qrCode;
case 'connecting':
return instance.qrCode;
default:
return info?.status;
}
} catch (error) {
this.logger.error(error);
throw new BadRequestException(error?.message);
}
}
public async updateInstance(instance: InstanceDto) {
try {
const instanceData = await this.instanceService.updateInstance(instance);
return instanceData;
} catch (error) {
this.logger.error(error);
throw new BadRequestException(error?.message);
}
}
/**
* @deprecated
*/
public async connectionState({ instanceName }: InstanceDto) {
const instance = this.waMonitor.waInstances.get(instanceName);
if (!instance) {
return {
state: 'close',
statusReason: 400,
};
}
return this.waMonitor.waInstances.get(instanceName).getInstance().status;
}
public async fetchInstance({ instanceName }: InstanceDto) {
try {
const instance = (await this.instanceService.fetchInstance(instanceName))[0];
if (instance) {
const i = this.waMonitor.waInstances.get(instanceName);
if (i) {
instance['Whatsapp'] = {
connection: this.waMonitor.waInstances.get(instanceName).getInstance().status,
};
return instance;
}
instance['Whatsapp'] = {
connection: {
state: 'close',
statusReason: 400,
},
};
return instance;
}
throw new Error('Instance not found');
} catch (error) {
throw new BadRequestException(error?.message);
}
}
public async fetchInstances({ instanceName }: InstanceDto) {
if (instanceName && !isString(instanceName)) {
throw new BadRequestException('instanceName must be a string');
}
if (instanceName) {
const i = await this.instanceService.fetchInstance(instanceName);
if (i.length === 0) {
throw new BadRequestException('Instance not found');
}
return i;
}
return await this.instanceService.fetchInstance();
}
public async logout({ instanceName }: InstanceDto) {
try {
await this.waMonitor.waInstances
.get(instanceName)
?.client?.logout('Log out instance: ' + instanceName);
return { error: false, message: 'Instance logged out' };
} catch (error) {
throw new InternalServerErrorException(error?.message);
}
}
public async deleteInstance({ instanceName }: InstanceDto, force?: boolean) {
const instance = this.waMonitor.waInstances.get(instanceName);
if (instance && instance.getInstance()?.status?.state === 'open') {
throw new BadRequestException([
'Deletion failed',
'The instance needs to be disconnected',
]);
}
const del = await this.instanceService.deleteInstance({ instanceName }, force);
del['deletedAt'] = new Date();
return del;
}
public async refreshToken(instance: InstanceDto, oldToken: OldToken, req: Request) {
const token = await this.instanceService.refreshToken(oldToken);
req.session[instance.instanceName] = Buffer.from(JSON.stringify(token)).toString(
'base64',
);
}
}