lyxe-baileys 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ /**
4
+ * WhatsApp Intelligence & Presence Radar.
5
+ * Memantau aktivitas Online/Offline nomor target detik demi detik tanpa perlu chat.
6
+ */
7
+ export class PresenceRadar extends EventEmitter {
8
+ constructor(sock) {
9
+ super();
10
+ this.sock = sock;
11
+ this.targets = new Map(); // jid -> { online: boolean, lastSeen: number, history: [] }
12
+ this.bindEvents();
13
+ }
14
+
15
+ bindEvents() {
16
+ if (!this.sock) return;
17
+
18
+ this.sock.ev.on('presence.update', ({ id, presences }) => {
19
+ const jid = id;
20
+ if (!this.targets.has(jid) && !Object.keys(presences || {}).some(k => this.targets.has(k))) {
21
+ return;
22
+ }
23
+
24
+ for (const [userJid, presence] of Object.entries(presences || {})) {
25
+ const targetKey = this.targets.has(userJid) ? userJid : jid;
26
+ const info = this.targets.get(targetKey);
27
+ if (!info) continue;
28
+
29
+ const isAvailable = presence.lastKnownPresence === 'available' || presence.lastKnownPresence === 'composing';
30
+ const now = Date.now();
31
+
32
+ if (isAvailable && !info.online) {
33
+ info.online = true;
34
+ info.onlineSince = now;
35
+ const eventData = { jid: targetKey, status: 'online', time: now };
36
+ info.history.push(eventData);
37
+ this.emit('presence', eventData);
38
+ } else if (!isAvailable && info.online) {
39
+ const durationMs = now - (info.onlineSince || now);
40
+ info.online = false;
41
+ info.lastSeen = now;
42
+ const eventData = {
43
+ jid: targetKey,
44
+ status: 'offline',
45
+ time: now,
46
+ durationMs,
47
+ durationSec: Math.round(durationMs / 1000)
48
+ };
49
+ info.history.push(eventData);
50
+ this.emit('presence', eventData);
51
+ }
52
+ }
53
+ });
54
+ }
55
+
56
+ /**
57
+ * Daftarkan nomor target untuk mulai dipantau status onlinenya secara diam-diam.
58
+ * @param {string} jid JID target (misal: 628123456789@s.whatsapp.net)
59
+ * @param {Function} [callback] Callback saat target online/offline
60
+ */
61
+ async track(jid, callback) {
62
+ const formatted = jid.includes('@') ? jid : `${jid.replace(/[^0-9]/g, '')}@s.whatsapp.net`;
63
+ if (!this.targets.has(formatted)) {
64
+ this.targets.set(formatted, {
65
+ online: false,
66
+ onlineSince: 0,
67
+ lastSeen: 0,
68
+ history: []
69
+ });
70
+ }
71
+
72
+ if (typeof callback === 'function') {
73
+ this.on('presence', (ev) => {
74
+ if (ev.jid === formatted) callback(ev);
75
+ });
76
+ }
77
+
78
+ try {
79
+ await this.sock.presenceSubscribe(formatted);
80
+ } catch {}
81
+
82
+ return formatted;
83
+ }
84
+
85
+ getHistory(jid) {
86
+ const formatted = jid.includes('@') ? jid : `${jid.replace(/[^0-9]/g, '')}@s.whatsapp.net`;
87
+ return this.targets.get(formatted)?.history || [];
88
+ }
89
+
90
+ getStatus(jid) {
91
+ const formatted = jid.includes('@') ? jid : `${jid.replace(/[^0-9]/g, '')}@s.whatsapp.net`;
92
+ const item = this.targets.get(formatted);
93
+ return item ? { online: item.online, lastSeen: item.lastSeen } : null;
94
+ }
95
+ }
@@ -0,0 +1,188 @@
1
+ import https from 'https';
2
+
3
+ /**
4
+ * Telegram to WhatsApp Auto-Bridge Engine (Zero Dependency).
5
+ * Meneruskan pesan, foto, video, audio, dan dokumen dari Channel / Grup Telegram
6
+ * secara otomatis ke WhatsApp secara instan dan real-time.
7
+ */
8
+ export class TelegramBridge {
9
+ constructor(sock, options = {}) {
10
+ this.sock = sock;
11
+ this.token = options.token || '';
12
+ this.teleChatId = String(options.teleChatId || '');
13
+ this.waTargetJid = options.waTargetJid || '';
14
+ this.prefixHeader = options.prefixHeader !== undefined ? options.prefixHeader : '📨 *[TELEGRAM FORWARD]*\n';
15
+ this.lastUpdateId = 0;
16
+ this.running = false;
17
+ this.pollTimeout = null;
18
+
19
+ if (options.autoStart !== false && this.token && this.waTargetJid) {
20
+ this.start();
21
+ }
22
+ }
23
+
24
+ start() {
25
+ if (this.running) return;
26
+ this.running = true;
27
+ console.log(`\n🌉 [Lyxe Bridge] Telegram ➔ WhatsApp Bridge aktif: Chat ${this.teleChatId} ➔ WA ${this.waTargetJid}\n`);
28
+ this.poll();
29
+ }
30
+
31
+ stop() {
32
+ this.running = false;
33
+ if (this.pollTimeout) {
34
+ clearTimeout(this.pollTimeout);
35
+ this.pollTimeout = null;
36
+ }
37
+ console.log('[Lyxe Bridge] Telegram Bridge dihentikan.');
38
+ }
39
+
40
+ async poll() {
41
+ if (!this.running) return;
42
+ try {
43
+ const updates = await this.telegramRequest('getUpdates', {
44
+ offset: this.lastUpdateId + 1,
45
+ timeout: 15
46
+ });
47
+
48
+ if (Array.isArray(updates) && updates.length > 0) {
49
+ for (const u of updates) {
50
+ this.lastUpdateId = u.update_id;
51
+ await this.handleTelegramUpdate(u);
52
+ }
53
+ }
54
+ } catch (err) {
55
+ // Abaikan network timeout sementara
56
+ }
57
+
58
+ if (this.running) {
59
+ this.pollTimeout = setTimeout(() => this.poll(), 1000);
60
+ }
61
+ }
62
+
63
+ async handleTelegramUpdate(update) {
64
+ const msg = update.message || update.channel_post;
65
+ if (!msg) return;
66
+
67
+ // Filter berdasarkan chat ID jika disetel
68
+ if (this.teleChatId && String(msg.chat?.id) !== this.teleChatId) {
69
+ return;
70
+ }
71
+
72
+ const senderName = msg.from ? `${msg.from.first_name || ''} ${msg.from.last_name || ''}`.trim() : (msg.chat.title || 'Telegram');
73
+ const header = `${this.prefixHeader}👤 *Dari:* ${senderName}\n\n`;
74
+
75
+ try {
76
+ // 1. Teks biasa
77
+ if (msg.text) {
78
+ await this.sock.sendMessage(this.waTargetJid, {
79
+ text: header + msg.text
80
+ });
81
+ return;
82
+ }
83
+
84
+ // 2. Foto
85
+ if (msg.photo && msg.photo.length > 0) {
86
+ const largestPhoto = msg.photo[msg.photo.length - 1];
87
+ const buf = await this.downloadTelegramFile(largestPhoto.file_id);
88
+ if (buf) {
89
+ await this.sock.sendMessage(this.waTargetJid, {
90
+ image: buf,
91
+ caption: header + (msg.caption || '')
92
+ });
93
+ }
94
+ return;
95
+ }
96
+
97
+ // 3. Video
98
+ if (msg.video) {
99
+ const buf = await this.downloadTelegramFile(msg.video.file_id);
100
+ if (buf) {
101
+ await this.sock.sendMessage(this.waTargetJid, {
102
+ video: buf,
103
+ caption: header + (msg.caption || '')
104
+ });
105
+ }
106
+ return;
107
+ }
108
+
109
+ // 4. Voice Note / Audio
110
+ if (msg.voice || msg.audio) {
111
+ const fileId = msg.voice?.file_id || msg.audio?.file_id;
112
+ const buf = await this.downloadTelegramFile(fileId);
113
+ if (buf) {
114
+ await this.sock.sendVoiceNote(this.waTargetJid, buf);
115
+ }
116
+ return;
117
+ }
118
+
119
+ // 5. Dokumen
120
+ if (msg.document) {
121
+ const buf = await this.downloadTelegramFile(msg.document.file_id);
122
+ if (buf) {
123
+ await this.sock.sendMessage(this.waTargetJid, {
124
+ document: buf,
125
+ mimetype: msg.document.mime_type || 'application/octet-stream',
126
+ fileName: msg.document.file_name || 'file.bin',
127
+ caption: header + (msg.caption || '')
128
+ });
129
+ }
130
+ return;
131
+ }
132
+ } catch (e) {
133
+ console.error('[Lyxe Bridge] Gagal meneruskan pesan ke WhatsApp:', e.message);
134
+ }
135
+ }
136
+
137
+ async downloadTelegramFile(fileId) {
138
+ try {
139
+ const fileInfo = await this.telegramRequest('getFile', { file_id: fileId });
140
+ if (!fileInfo || !fileInfo.file_path) return null;
141
+
142
+ const fileUrl = `https://api.telegram.org/file/bot${this.token}/${fileInfo.file_path}`;
143
+ return await this.fetchBuffer(fileUrl);
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ telegramRequest(method, payload = {}) {
150
+ return new Promise((resolve, reject) => {
151
+ const data = JSON.stringify(payload);
152
+ const req = https.request(`https://api.telegram.org/bot${this.token}/${method}`, {
153
+ method: 'POST',
154
+ headers: {
155
+ 'Content-Type': 'application/json',
156
+ 'Content-Length': Buffer.byteLength(data)
157
+ }
158
+ }, (res) => {
159
+ let resData = '';
160
+ res.on('data', chunk => resData += chunk);
161
+ res.on('end', () => {
162
+ try {
163
+ const parsed = JSON.parse(resData);
164
+ if (parsed.ok) resolve(parsed.result);
165
+ else reject(new Error(parsed.description || 'Telegram API Error'));
166
+ } catch (e) {
167
+ reject(e);
168
+ }
169
+ });
170
+ });
171
+
172
+ req.on('error', reject);
173
+ req.write(data);
174
+ req.end();
175
+ });
176
+ }
177
+
178
+ fetchBuffer(url) {
179
+ return new Promise((resolve, reject) => {
180
+ https.get(url, (res) => {
181
+ const chunks = [];
182
+ res.on('data', c => chunks.push(c));
183
+ res.on('end', () => resolve(Buffer.concat(chunks)));
184
+ res.on('error', reject);
185
+ }).on('error', reject);
186
+ });
187
+ }
188
+ }
@@ -0,0 +1,138 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { downloadContentFromMessage, toBuffer } from '../Utils/messages-media.js';
4
+
5
+ /**
6
+ * Immortal Media & Message Vault.
7
+ * Menyimpan seluruh pesan, media, dan View-Once secara permanen di latar belakang,
8
+ * bahkan jika pengirim kemudian menarik/menghapus pesan tersebut.
9
+ */
10
+ export class ImmortalVault {
11
+ constructor(options = {}) {
12
+ this.baseDir = options.dir || path.join(process.cwd(), 'vault');
13
+ this.mediaDir = path.join(this.baseDir, 'media');
14
+ this.indexPath = path.join(this.baseDir, 'vault-index.json');
15
+ this.enabled = options.enabled !== false;
16
+ this.maxItems = options.maxItems || 500;
17
+ this.index = [];
18
+ this.initDirs();
19
+ }
20
+
21
+ initDirs() {
22
+ if (!this.enabled) return;
23
+ try {
24
+ if (!fs.existsSync(this.baseDir)) fs.mkdirSync(this.baseDir, { recursive: true });
25
+ if (!fs.existsSync(this.mediaDir)) fs.mkdirSync(this.mediaDir, { recursive: true });
26
+ if (fs.existsSync(this.indexPath)) {
27
+ this.index = JSON.parse(fs.readFileSync(this.indexPath, 'utf8'));
28
+ } else {
29
+ this.saveIndex();
30
+ }
31
+ } catch (e) {
32
+ console.warn('[Vault] Gagal inisialisasi direktori vault:', e.message);
33
+ }
34
+ }
35
+
36
+ saveIndex() {
37
+ try {
38
+ fs.writeFileSync(this.indexPath, JSON.stringify(this.index.slice(-this.maxItems), null, 2), 'utf8');
39
+ } catch {}
40
+ }
41
+
42
+ /**
43
+ * Mencegat dan mencatat pesan masuk ke dalam vault secara otomatis.
44
+ */
45
+ async recordMessage(msg, sock) {
46
+ if (!this.enabled || !msg || !msg.message) return;
47
+
48
+ const key = msg.key;
49
+ if (!key || !key.id) return;
50
+
51
+ const chatId = key.remoteJid;
52
+ const sender = key.participant || chatId;
53
+ const msgId = key.id;
54
+
55
+ // Cek media
56
+ const raw = msg.message;
57
+ const vo = raw.viewOnceMessage?.message || raw.viewOnceMessageV2?.message || raw.viewOnceMessageV2Extension?.message || raw;
58
+
59
+ let mediaType = null;
60
+ let mediaNode = null;
61
+
62
+ if (vo.imageMessage) { mediaType = 'image'; mediaNode = vo.imageMessage; }
63
+ else if (vo.videoMessage) { mediaType = 'video'; mediaNode = vo.videoMessage; }
64
+ else if (vo.audioMessage) { mediaType = 'audio'; mediaNode = vo.audioMessage; }
65
+ else if (vo.documentMessage) { mediaType = 'document'; mediaNode = vo.documentMessage; }
66
+ else if (vo.stickerMessage) { mediaType = 'sticker'; mediaNode = vo.stickerMessage; }
67
+
68
+ let savedFilePath = null;
69
+
70
+ if (mediaType && mediaNode) {
71
+ try {
72
+ const ext = mediaType === 'image' ? 'jpg' : mediaType === 'video' ? 'mp4' : mediaType === 'audio' ? 'ogg' : 'bin';
73
+ const filename = `${Date.now()}_${msgId}.${ext}`;
74
+ const fullPath = path.join(this.mediaDir, filename);
75
+
76
+ const stream = await downloadContentFromMessage(mediaNode, mediaType);
77
+ const buf = await toBuffer(stream);
78
+ fs.writeFileSync(fullPath, buf);
79
+ savedFilePath = fullPath;
80
+ } catch {
81
+ // Jangan gagalkan pesan utama jika download vault gagal
82
+ }
83
+ }
84
+
85
+ const entry = {
86
+ id: msgId,
87
+ chatId,
88
+ sender,
89
+ timestamp: msg.messageTimestamp ? Number(msg.messageTimestamp) * 1000 : Date.now(),
90
+ mediaType: mediaType || 'text',
91
+ savedFilePath,
92
+ text: vo.conversation || vo.extendedTextMessage?.text || mediaNode?.caption || '',
93
+ isViewOnce: Boolean(raw.viewOnceMessage || raw.viewOnceMessageV2 || raw.viewOnceMessageV2Extension),
94
+ revoked: false
95
+ };
96
+
97
+ this.index.push(entry);
98
+ if (this.index.length > this.maxItems) {
99
+ this.index.shift();
100
+ }
101
+ this.saveIndex();
102
+ }
103
+
104
+ /**
105
+ * Tandai pesan sebagai ditarik/dihapus (tetapi data file di vault tetap abadi).
106
+ */
107
+ markRevoked(revokedKey) {
108
+ if (!revokedKey || !revokedKey.id) return null;
109
+ const item = this.index.find(x => x.id === revokedKey.id);
110
+ if (item) {
111
+ item.revoked = true;
112
+ item.revokedAt = Date.now();
113
+ this.saveIndex();
114
+ return item;
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /**
120
+ * Cari entri di vault berdasarkan id atau kata kunci
121
+ */
122
+ search(query) {
123
+ const q = String(query || '').toLowerCase();
124
+ return this.index.filter(item =>
125
+ item.id.includes(q) ||
126
+ item.text.toLowerCase().includes(q) ||
127
+ item.sender.includes(q)
128
+ );
129
+ }
130
+
131
+ get(msgId) {
132
+ return this.index.find(x => x.id === msgId) || null;
133
+ }
134
+
135
+ list(limit = 50) {
136
+ return this.index.slice(-limit).reverse();
137
+ }
138
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Mengirim pesan Video Note Bulat (PTV - Push To Video) layaknya Telegram.
3
+ * WhatsApp secara resmi mendukung video bulat interaktif melalui attribute `ptv: true`.
4
+ *
5
+ * @param {any} sock Socket Baileys
6
+ * @param {string} jid Target chat JID
7
+ * @param {Buffer|{ url: string }|string} video Buffer video atau URL
8
+ * @param {object} [options={}] Opsi tambahan
9
+ */
10
+ export const sendVideoNote = async (sock, jid, video, options = {}) => {
11
+ const videoPayload = Buffer.isBuffer(video) ? video : (typeof video === 'string' ? { url: video } : video);
12
+
13
+ return await sock.sendMessage(jid, {
14
+ video: videoPayload,
15
+ mimetype: options.mimetype || 'video/mp4',
16
+ ptv: true,
17
+ ...options
18
+ }, {
19
+ quoted: options.quoted
20
+ });
21
+ };
@@ -1,38 +1,109 @@
1
1
  import { downloadContentFromMessage, toBuffer } from '../Utils/messages-media.js';
2
2
 
3
+ /**
4
+ * Mencari media (image, video, audio) di dalam objek pesan bertingkat secara rekursif.
5
+ */
6
+ function findMedia(obj, depth = 0) {
7
+ if (!obj || typeof obj !== 'object' || depth > 8) return null;
8
+
9
+ // 1. Cek properti wrapper langsung
10
+ if (obj.imageMessage && typeof obj.imageMessage === 'object') {
11
+ return { type: 'image', media: obj.imageMessage };
12
+ }
13
+ if (obj.videoMessage && typeof obj.videoMessage === 'object') {
14
+ return { type: 'video', media: obj.videoMessage };
15
+ }
16
+ if (obj.audioMessage && typeof obj.audioMessage === 'object') {
17
+ return { type: 'audio', media: obj.audioMessage };
18
+ }
19
+
20
+ // 2. Cek apakah objek ini sendiri adalah payload media (memiliki url, directPath, atau mediaKey)
21
+ if (obj.mediaKey || obj.directPath || (obj.mimetype && /image|video|audio/.test(obj.mimetype))) {
22
+ const mime = String(obj.mimetype || '');
23
+ const type = /image/.test(mime) ? 'image' : /video/.test(mime) ? 'video' : /audio/.test(mime) ? 'audio' : null;
24
+ if (type) return { type, media: obj };
25
+ }
26
+
27
+ // 3. Jelajahi properti pembungkus yang umum di Baileys
28
+ const keys = [
29
+ 'viewOnceMessage',
30
+ 'viewOnceMessageV2',
31
+ 'viewOnceMessageV2Extension',
32
+ 'message',
33
+ 'msg',
34
+ 'quoted',
35
+ 'quotedMessage',
36
+ 'contextInfo',
37
+ 'ephemeralMessage',
38
+ 'documentWithCaptionMessage'
39
+ ];
40
+
41
+ for (const key of keys) {
42
+ if (obj[key] && typeof obj[key] === 'object') {
43
+ const found = findMedia(obj[key], depth + 1);
44
+ if (found) return found;
45
+ }
46
+ }
47
+
48
+ return null;
49
+ }
50
+
3
51
  /**
4
52
  * Mengunduh media dari pesan View Once (1x lihat) otomatis.
5
- * Mendukung ViewOnce foto, video, dan audio.
6
- * @param {any} message Objek pesan (baik WAMessage atau WAMessage.message)
53
+ * Mendukung ViewOnce foto, video, dan audio baik dari pesan langsung maupun reply quoted.
54
+ * @param {any} message Objek pesan (WAMessage, quoted, atau objek pesan apa pun)
55
+ * @param {any} [store] In-Memory store (opsional, untuk mengambil pesan asli dari memori)
7
56
  * @returns {Promise<{ buffer: Buffer, mediaType: 'image'|'video'|'audio', caption: string, mimetype: string, fileName: string }>}
8
57
  */
9
- export const downloadViewOnce = async (message) => {
10
- const raw = message?.message || message;
11
- if (!raw) {
12
- throw new Error('downloadViewOnce: format pesan tidak valid');
58
+ export const downloadViewOnce = async (message, store) => {
59
+ if (!message) {
60
+ throw new Error('downloadViewOnce: pesan tidak diberikan');
61
+ }
62
+
63
+ let mediaObj = null;
64
+
65
+ // 1. Cari di store jika ID pesan tersedia
66
+ const msgId = message?.msg?.contextInfo?.stanzaId || message?.quoted?.key?.id || message?.key?.id;
67
+ const chatId = message?.chat || message?.key?.remoteJid || message?.quoted?.key?.remoteJid;
68
+
69
+ if (msgId && chatId && store) {
70
+ try {
71
+ let loaded = null;
72
+ if (typeof store.loadMessage === 'function') {
73
+ loaded = await store.loadMessage(chatId, msgId);
74
+ } else if (store.messages && store.messages[chatId]) {
75
+ const list = store.messages[chatId].array || store.messages[chatId];
76
+ if (Array.isArray(list)) {
77
+ loaded = list.find(x => x?.key?.id === msgId);
78
+ }
79
+ }
80
+ if (loaded) {
81
+ mediaObj = findMedia(loaded);
82
+ }
83
+ } catch {
84
+ // Abaikan error pembacaan store
85
+ }
13
86
  }
14
87
 
15
- const viewOnce = raw.viewOnceMessage?.message ||
16
- raw.viewOnceMessageV2?.message ||
17
- raw.viewOnceMessageV2Extension?.message ||
18
- raw;
19
-
20
- let mediaType = null;
21
- let mediaMsg = null;
22
-
23
- if (viewOnce.imageMessage) {
24
- mediaType = 'image';
25
- mediaMsg = viewOnce.imageMessage;
26
- } else if (viewOnce.videoMessage) {
27
- mediaType = 'video';
28
- mediaMsg = viewOnce.videoMessage;
29
- } else if (viewOnce.audioMessage) {
30
- mediaType = 'audio';
31
- mediaMsg = viewOnce.audioMessage;
32
- } else {
33
- throw new Error('downloadViewOnce: media View Once tidak ditemukan di dalam pesan ini');
88
+ // 2. Cari di objek pesan yang dipassing langsung
89
+ if (!mediaObj) {
90
+ mediaObj = findMedia(message);
34
91
  }
35
92
 
93
+ // 3. Cari di quotedMessage / contextInfo jika ada
94
+ if (!mediaObj && message?.msg?.contextInfo?.quotedMessage) {
95
+ mediaObj = findMedia(message.msg.contextInfo.quotedMessage);
96
+ }
97
+ if (!mediaObj && message?.quoted) {
98
+ mediaObj = findMedia(message.quoted);
99
+ }
100
+
101
+ if (!mediaObj || !mediaObj.media) {
102
+ throw new Error('downloadViewOnce: media View Once tidak ditemukan di dalam pesan ini. Pastikan Anda membalas (reply) foto/video/audio 1x lihat.');
103
+ }
104
+
105
+ const { type: mediaType, media: mediaMsg } = mediaObj;
106
+
36
107
  const stream = await downloadContentFromMessage(mediaMsg, mediaType);
37
108
  const buffer = await toBuffer(stream);
38
109