File size: 6,527 Bytes
fb15d01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ============================================================
// N.E.X.A — TASKER INFRASTRUCTURE CLIENT
// Outbound Client untuk berkomunikasi dari N.E.X.A Core Server (HF Space)
// menuju perangkat Android Tuan Faqih (Tasker & ntfy.sh Gateway).
// ============================================================
'use strict';

const axios = require('axios');
const env = require('../config/env');
const security = require('../utils/security');

/**
 * Cek apakah ntfy.sh push gateway sudah dikonfigurasi di .env
 * @returns {boolean}
 */
function isNtfyConfigured() {
  return Boolean(env.NTFY_TOPIC && String(env.NTFY_TOPIC).trim() !== '');
}

/**
 * Cek apakah direct webhook Tasker sudah dikonfigurasi di .env
 * @returns {boolean}
 */
function isDirectWebhookConfigured() {
  return Boolean(env.TASKER_WEBHOOK_URL && String(env.TASKER_WEBHOOK_URL).trim() !== '');
}

/**
 * Cek apakah ada minimal satu jalur koneksi ke Tasker/Android (ntfy atau direct)
 * @returns {boolean}
 */
function isConfigured() {
  return isNtfyConfigured() || isDirectWebhookConfigured();
}

/**
 * Mengirim notifikasi push instan ke Android via ntfy.sh.
 * Sangat ideal untuk eksekusi sub-detik dan menembus mode Do Not Disturb (DND).
 * 
 * @param {string} message - Isi pesan notifikasi
 * @param {Object} [options] - Opsi header tambahan
 * @param {string} [options.title='N.E.X.A Alert'] - Judul notifikasi
 * @param {string} [options.priority='default'] - Prioritas ('min', 'low', 'default', 'high', 'urgent')
 * @param {string} [options.tags='robot'] - Tag/emoji untuk ntfy (misal: 'warning,skull')
 * @returns {Promise<boolean>} true jika berhasil, false jika gagal
 */
async function pushNtfy(message, options = {}) {
  if (!isNtfyConfigured()) {
    console.warn('[TASKER CLIENT] NTFY_TOPIC not configured. Push via ntfy.sh disabled.');
    return false;
  }

  const {
    title = 'N.E.X.A Alert',
    priority = 'default',
    tags = 'robot'
  } = options;

  const startTime = Date.now();
  const summaryMsg = message.length > 80 ? message.substring(0, 80) + '...' : message;
  console.log(`[NTFY PUSH] Sending to topic "${env.NTFY_TOPIC}" | Title: "${title}" | Tags: [${tags}] | Preview: "${summaryMsg}"`);

  try {
    await axios.post(`https://ntfy.sh/${env.NTFY_TOPIC}`, message, {
      headers: {
        'Title': title,
        'Priority': priority,
        'Tags': tags
      },
      timeout: 5000
    });
    const elapsed = Date.now() - startTime;
    console.log(`[NTFY PUSH] Push delivered successfully in ${elapsed}ms!`);
    return true;
  } catch (err) {
    console.error(`[NTFY PUSH ERROR] Failed to send push after ${Date.now() - startTime}ms:`, err.message);
    return false;
  }
}

/**
 * Mengirim payload HTTP langsung ke endpoint Tasker (AutoRemote / ngrok / direct webhook).
 * Otomatis melampirkan HMAC SHA-256 signature pada header X-NEXA-Signature & Bearer Token.
 * 
 * @param {Object} commandPayload - Objek perintah untuk Tasker (misal: { type: 'GOD_MODE_ESCALATION', level: 3, actions: [...] })
 * @param {Object} [metadata={}] - Metadata kontekstual tambahan
 * @param {Object} [options={}] - Opsi tambahan (level eskalasi, timestamp kustom)
 * @param {number} [options.level=1] - Level eskalasi untuk HMAC signature
 * @param {string} [options.timestamp] - ISO timestamp (jika kosong, menggunakan waktu sekarang)
 * @returns {Promise<boolean>} true jika berhasil, false jika gagal
 */
async function sendDirectCommand(commandPayload, metadata = {}, options = {}) {
  if (!isDirectWebhookConfigured()) {
    return false;
  }

  const level = options.level || commandPayload?.level || 1;
  const timestamp = options.timestamp || new Date().toISOString();
  const signature = security.generateTaskerSignature(timestamp, level);

  const payload = {
    auth: {
      bearer_token: env.NEXA_GODMODE_SECRET,
      timestamp: timestamp
    },
    command: commandPayload,
    metadata: metadata
  };

  try {
    await axios.post(env.TASKER_WEBHOOK_URL, payload, {
      headers: {
        'Authorization': `Bearer ${env.NEXA_GODMODE_SECRET}`,
        'Content-Type': 'application/json',
        'X-NEXA-Signature': signature
      },
      timeout: 5000
    });
    return true;
  } catch (err) {
    console.warn('[TASKER CLIENT] Direct Tasker push failed:', err.message);
    return false;
  }
}

/**
 * Mengirimkan perintah via Mobile Bridge WebSocket (Kanal Primer)
 * 
 * @param {string} actionType - Nama aksi (misal: 'DISABLE_WIFI', 'SET_ALARM')
 * @param {Object} [params={}] - Parameter aksi
 * @param {number} [level=1] - Level eskalasi
 * @returns {boolean} true jika terkirim via WebSocket, false jika offline
 */
function sendViaMobileBridge(actionType, params = {}, level = 1) {
  try {
    const mobileBridge = require('../interfaces/mobile_bridge/MobileBridge_WS');
    return mobileBridge.sendCommand(actionType, params, level);
  } catch (e) {
    console.error('[TASKER CLIENT] Mobile Bridge error:', e.message);
    return false;
  }
}

/**
 * Mengirimkan tindakan sistem standar ke Tasker (misal: mematikan Wi-Fi, menyalakan alarm, dll.)
 * Menggunakan MobileBridge (Primer), ntfy.sh (Sekunder), dan sendDirectCommand (Tersier/Fallback).
 * 
 * @param {string} actionType - Nama aksi (misal: 'DISABLE_WIFI', 'SET_ALARM')
 * @param {Object} [params={}] - Parameter aksi
 * @param {Object} [options={}] - Opsi push
 * @returns {Promise<{ wsSent: boolean, ntfySent: boolean, directSent: boolean }>} Status pengiriman
 */
async function sendSystemAction(actionType, params = {}, options = {}) {
  const {
    title = `N.E.X.A Action: ${actionType}`,
    priority = 'high',
    tags = 'gear',
    level = 1
  } = options;

  // 1. Coba WebSocket (Kanal Primer - Paling Cepat & Senyap)
  const wsSent = sendViaMobileBridge(actionType, params, level);
  
  let ntfySent = false;
  let directSent = false;

  // 2. Jika WebSocket offline, gunakan Ntfy (Kanal Sekunder)
  if (!wsSent) {
    const ntfyMessage = `[ACTION] ${actionType}\n${JSON.stringify(params, null, 2)}`;
    ntfySent = await pushNtfy(ntfyMessage, { title, priority, tags });
  }

  // 3. Fallback Tasker Webhook (Kanal Tersier)
  if (!wsSent) {
    directSent = await sendDirectCommand({
      type: 'SYSTEM_ACTION',
      level: level,
      actions: [{ action: actionType, params }]
    }, {}, { level });
  }

  return { wsSent, ntfySent, directSent };
}

module.exports = {
  isConfigured,
  isNtfyConfigured,
  isDirectWebhookConfigured,
  pushNtfy,
  sendDirectCommand,
  sendSystemAction,
  sendViaMobileBridge
};