File size: 5,433 Bytes
464b662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Body, Controller, Post, Res, HttpStatus } from '@nestjs/common';
import { WhatsappService } from '../whatsapp/whatsapp.service';
import { formatJid } from '../common/utils';

class TextMessageBody {
  target!: string;
  message!: string;
}

class MediaMessageBody {
  target!: string;
  url!: string;
  caption?: string;
  filename?: string;
  mimetype?: string;
}

class PollMessageBody {
  target!: string;
  question!: string;
  options!: string[];
  multiSelect?: boolean;
}

@Controller('send')
export class MessageController {
  constructor(private readonly whatsappService: WhatsappService) {}

  private handleRouteError(err: unknown, res: any): void {
    const message = err instanceof Error ? err.message : 'Unknown error';
    const statusCode = message.includes('belum terhubung')
      ? HttpStatus.SERVICE_UNAVAILABLE
      : HttpStatus.INTERNAL_SERVER_ERROR;
    console.error(`Error Pengiriman: ${message}`);
    res.status(statusCode).json({ status: 'Error', message });
  }

  @Post('/')
  async sendText(@Body() body: TextMessageBody, @Res() res: any) {
    const { target, message } = body;

    if (!target || !message) {
      return res.status(HttpStatus.BAD_REQUEST).json({
        status: 'Error',
        message: 'Field "target" dan "message" wajib diisi.',
      });
    }

    try {
      const sock = this.whatsappService.getSocket();
      const jid = formatJid(target);

      if (jid.endsWith('@g.us')) {
        await this.whatsappService.groupCacheReady;
      }

      // ⚠️ PERHATIAN: Tidak Boleh menggunakan withTimeout di sini.
      // Jika disinkron ke 1000 anggota pertama kalinya dan butuh waktu 2 menit,
      // kita harus rela menunggu janji Baileys terpenuhi.
      // Terminate paksa promise ini hanya akan membuat mutex Baileys hang seumur hidup.
      await sock.sendMessage(jid, { text: message });

      console.log(`πŸ“€ [TEXT] β†’ ${jid} (Sukses)`);
      res
        .status(HttpStatus.OK)
        .json({ status: 'Success', type: 'text', to: jid });
    } catch (err) {
      this.handleRouteError(err, res);
    }
  }

  @Post('/image')
  async sendImage(@Body() body: MediaMessageBody, @Res() res: any) {
    const { target, url, caption } = body;
    if (!target || !url) {
      return res
        .status(HttpStatus.BAD_REQUEST)
        .json({ status: 'Error', message: 'target & url wajib.' });
    }
    try {
      const sock = this.whatsappService.getSocket();
      const jid = formatJid(target);
      if (jid.endsWith('@g.us')) await this.whatsappService.groupCacheReady;

      await sock.sendMessage(jid, { image: { url }, caption: caption ?? '' });

      console.log(`πŸ“€ [IMAGE] β†’ ${jid}`);
      res
        .status(HttpStatus.OK)
        .json({ status: 'Success', type: 'image', to: jid });
    } catch (err) {
      this.handleRouteError(err, res);
    }
  }

  @Post('/video')
  async sendVideo(@Body() body: MediaMessageBody, @Res() res: any) {
    const { target, url, caption } = body;
    if (!target || !url) {
      return res
        .status(HttpStatus.BAD_REQUEST)
        .json({ status: 'Error', message: 'target & url wajib.' });
    }
    try {
      const sock = this.whatsappService.getSocket();
      const jid = formatJid(target);
      if (jid.endsWith('@g.us')) await this.whatsappService.groupCacheReady;

      await sock.sendMessage(jid, { video: { url }, caption: caption ?? '' });

      console.log(`πŸ“€ [VIDEO] β†’ ${jid}`);
      res
        .status(HttpStatus.OK)
        .json({ status: 'Success', type: 'video', to: jid });
    } catch (err) {
      this.handleRouteError(err, res);
    }
  }

  @Post('/document')
  async sendDocument(@Body() body: MediaMessageBody, @Res() res: any) {
    const { target, url, filename, mimetype } = body;
    if (!target || !url || !filename) {
      return res
        .status(HttpStatus.BAD_REQUEST)
        .json({ status: 'Error', message: 'target, url & filename wajib.' });
    }
    try {
      const sock = this.whatsappService.getSocket();
      const jid = formatJid(target);
      if (jid.endsWith('@g.us')) await this.whatsappService.groupCacheReady;

      await sock.sendMessage(jid, {
        document: { url },
        fileName: filename,
        mimetype: mimetype ?? 'application/octet-stream',
      });

      console.log(`πŸ“€ [DOC] β†’ ${jid}`);
      res
        .status(HttpStatus.OK)
        .json({ status: 'Success', type: 'document', to: jid });
    } catch (err) {
      this.handleRouteError(err, res);
    }
  }

  @Post('/poll')
  async sendPoll(@Body() body: PollMessageBody, @Res() res: any) {
    const { target, question, options, multiSelect } = body;
    if (!target || !question || !options || options.length < 2) {
      return res
        .status(HttpStatus.BAD_REQUEST)
        .json({ status: 'Error', message: 'Opsi poll minimal 2' });
    }
    try {
      const sock = this.whatsappService.getSocket();
      const jid = formatJid(target);
      if (jid.endsWith('@g.us')) await this.whatsappService.groupCacheReady;

      await sock.sendMessage(jid, {
        poll: {
          name: question,
          values: options,
          selectableCount: multiSelect ? options.length : 1,
        },
      });

      console.log(`πŸ“€ [POLL] β†’ ${jid}`);
      res
        .status(HttpStatus.OK)
        .json({ status: 'Success', type: 'poll', to: jid });
    } catch (err) {
      this.handleRouteError(err, res);
    }
  }
}