File size: 7,101 Bytes
5e518ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { EventDto } from '@api/integrations/event/event.dto';
import { PrismaRepository } from '@api/repository/repository.service';
import { WAMonitoringService } from '@api/services/monitor.service';
import { wa } from '@api/types/wa.types';
import { configService, Log, Pusher as ConfigPusher } from '@config/env.config';
import { Logger } from '@config/logger.config';
import Pusher from 'pusher';

import { EmitData, EventController, EventControllerInterface } from '../event.controller';
export class PusherController extends EventController implements EventControllerInterface {
  private readonly logger = new Logger('PusherController');
  private pusherClients: { [instanceName: string]: Pusher } = {};
  private globalPusherClient: Pusher | null = null;
  private pusherConfig: ConfigPusher = configService.get<ConfigPusher>('PUSHER');
  constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
    super(prismaRepository, waMonitor, configService.get<ConfigPusher>('PUSHER')?.ENABLED, 'pusher');
    this.init();
  }
  public async init(): Promise<void> {
    if (!this.status) {
      return;
    }
    if (this.pusherConfig.GLOBAL?.ENABLED) {
      const { APP_ID, KEY, SECRET, CLUSTER, USE_TLS } = this.pusherConfig.GLOBAL;
      if (APP_ID && KEY && SECRET && CLUSTER) {
        this.globalPusherClient = new Pusher({
          appId: APP_ID,
          key: KEY,
          secret: SECRET,
          cluster: CLUSTER,
          useTLS: USE_TLS,
        });
        this.logger.info('Pusher global client initialized');
      }
    }
    const instances = await this.prismaRepository.instance.findMany({
      where: {
        Pusher: {
          isNot: null,
        },
      },
      include: {
        Pusher: true,
      },
    });
    instances.forEach((instance) => {
      if (
        instance.Pusher.enabled &&
        instance.Pusher.appId &&
        instance.Pusher.key &&
        instance.Pusher.secret &&
        instance.Pusher.cluster
      ) {
        this.pusherClients[instance.name] = new Pusher({
          appId: instance.Pusher.appId,
          key: instance.Pusher.key,
          secret: instance.Pusher.secret,
          cluster: instance.Pusher.cluster,
          useTLS: instance.Pusher.useTLS,
        });
        this.logger.info(`Pusher client initialized for instance ${instance.name}`);
      } else {
        delete this.pusherClients[instance.name];
        this.logger.warn(`Pusher client disabled or misconfigured for instance ${instance.name}`);
      }
    });
  }
  override async set(instanceName: string, data: EventDto): Promise<wa.LocalPusher> {
    if (!data.pusher?.enabled) {
      data.pusher.events = [];
    } else if (data.pusher.events.length === 0) {
      data.pusher.events = EventController.events;
    }
    const instance = await this.prisma.pusher.upsert({
      where: {
        instanceId: this.monitor.waInstances[instanceName].instanceId,
      },
      update: {
        enabled: data.pusher.enabled,
        events: data.pusher.events,
        appId: data.pusher.appId,
        key: data.pusher.key,
        secret: data.pusher.secret,
        cluster: data.pusher.cluster,
        useTLS: data.pusher.useTLS,
      },
      create: {
        enabled: data.pusher.enabled,
        events: data.pusher.events,
        instanceId: this.monitor.waInstances[instanceName].instanceId,
        appId: data.pusher.appId,
        key: data.pusher.key,
        secret: data.pusher.secret,
        cluster: data.pusher.cluster,
        useTLS: data.pusher.useTLS,
      },
    });
    if (instance.enabled && instance.appId && instance.key && instance.secret && instance.cluster) {
      this.pusherClients[instanceName] = new Pusher({
        appId: instance.appId,
        key: instance.key,
        secret: instance.secret,
        cluster: instance.cluster,
        useTLS: instance.useTLS,
      });
      this.logger.info(`Pusher client initialized for instance ${instanceName}`);
    } else {
      delete this.pusherClients[instanceName];
      this.logger.warn(`Pusher client disabled or misconfigured for instance ${instanceName}`);
    }
    return instance;
  }
  public async emit({
    instanceName,
    origin,
    event,
    data,
    serverUrl,
    dateTime,
    sender,
    apiKey,
    local,
    integration,
  }: EmitData): Promise<void> {
    if (integration && !integration.includes('pusher')) {
      return;
    }
    if (!this.status) {
      return;
    }
    const instance = (await this.get(instanceName)) as wa.LocalPusher;
    const we = event.replace(/[.-]/gm, '_').toUpperCase();
    const enabledLog = configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS');
    const eventName = event.replace(/_/g, '.').toLowerCase();
    const pusherData = {
      event,
      instance: instanceName,
      data,
      destination: instance?.appId || this.pusherConfig.GLOBAL?.APP_ID,
      date_time: dateTime,
      sender,
      server_url: serverUrl,
      apikey: apiKey,
    };
    if (event == 'qrcode.updated') {
      delete pusherData.data.qrcode.base64;
    }
    const payload = JSON.stringify(pusherData);
    const payloadSize = Buffer.byteLength(payload, 'utf8');
    const MAX_SIZE = 10240;
    if (payloadSize > MAX_SIZE) {
      this.logger.error({
        local: `${origin}.sendData-Pusher`,
        message: 'Payload size exceeds Pusher limit',
        event,
        instanceName,
        payloadSize,
      });
      return;
    }
    if (local && instance && instance.enabled) {
      const pusherLocalEvents = instance.events;
      if (Array.isArray(pusherLocalEvents) && pusherLocalEvents.includes(we)) {
        if (enabledLog) {
          this.logger.log({
            local: `${origin}.sendData-Pusher`,
            appId: instance.appId,
            ...pusherData,
          });
        }
        try {
          const pusher = this.pusherClients[instanceName];
          if (pusher) {
            pusher.trigger(instanceName, eventName, pusherData);
          } else {
            this.logger.error(`Pusher client not found for instance ${instanceName}`);
          }
        } catch (error) {
          this.logger.error({
            local: `${origin}.sendData-Pusher`,
            message: error?.message,
            error,
          });
        }
      }
    }
    if (this.pusherConfig.GLOBAL?.ENABLED) {
      const globalEvents = this.pusherConfig.EVENTS;
      if (globalEvents[we]) {
        if (enabledLog) {
          this.logger.log({
            local: `${origin}.sendData-Pusher-Global`,
            appId: this.pusherConfig.GLOBAL?.APP_ID,
            ...pusherData,
          });
        }
        try {
          if (this.globalPusherClient) {
            this.globalPusherClient.trigger(instanceName, eventName, pusherData);
          } else {
            this.logger.error('Global Pusher client not initialized');
          }
        } catch (error) {
          this.logger.error({
            local: `${origin}.sendData-Pusher-Global`,
            message: error?.message,
            error,
          });
        }
      }
    }
  }
}