summaryrefslogtreecommitdiff
path: root/app/src/main/java/sh/lajo/buddy/WebSocketService.kt
blob: 100f0194e9f2ab4d978312471f1e4f6dbbfd5b45 (plain)
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package sh.lajo.buddy

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.Settings

import androidx.core.app.NotificationCompat

import android.util.Log
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener


class WebSocketService : Service() {

    companion object {
        const val ACTION_SEND_NOTIFICATION = "sh.lajo.buddy.action.SEND_NOTIFICATION"
        const val EXTRA_NOTIFICATION_TITLE = "sh.lajo.buddy.extra.NOTIFICATION_TITLE"
        const val EXTRA_NOTIFICATION_TEXT = "sh.lajo.buddy.extra.NOTIFICATION_TEXT"
        const val EXTRA_NOTIFICATION_PACKAGE = "sh.lajo.buddy.extra.NOTIFICATION_PACKAGE"
        const val ACTION_SEND_CONTACT = "sh.lajo.buddy.action.SEND_CONTACT"
        const val EXTRA_CONTACT_NAME = "sh.lajo.buddy.extra.CONTACT_NAME"
        const val EXTRA_CONTACT_PHONES = "sh.lajo.buddy.extra.CONTACT_PHONES"
        const val EXTRA_CONTACT_EMAILS = "sh.lajo.buddy.extra.CONTACT_EMAILS"
        const val ACTION_ACCESSIBILITY_MESSAGE = "sh.lajo.buddy.action.ACCESSIBILITY_MESSAGE"
        const val EXTRA_ACCESSIBILITY_APP = "sh.lajo.buddy.extra.ACCESSIBILITY_APP"
        const val EXTRA_ACCESSIBILITY_SENDER = "sh.lajo.buddy.extra.ACCESSIBILITY_SENDER"
        const val EXTRA_ACCESSIBILITY_MESSAGE_TEXT = "sh.lajo.buddy.extra.ACCESSIBILITY_MESSAGE_TEXT"
        const val EXTRA_ACCESSIBILITY_TIMESTAMP = "sh.lajo.buddy.extra.ACCESSIBILITY_TIMESTAMP"
        const val ACTION_CIRCUMVENTION_EVENT = "sh.lajo.buddy.action.CIRCUMVENTION_EVENT"
        const val EXTRA_CIRCUMVENTION_PACKAGE = "sh.lajo.buddy.extra.CIRCUMVENTION_PACKAGE"
        const val EXTRA_CIRCUMVENTION_CLASS = "sh.lajo.buddy.extra.CIRCUMVENTION_CLASS"
    }

    private lateinit var webSocket: WebSocket
    private val client = OkHttpClient()

    private var isConnected: Boolean = false
    private var isConnecting: Boolean = false
    private val pendingMessages = mutableListOf<String>()

    private var contactsObserver: ContactsObserver? = null

    var token: String = ""
    private val configFetchHandler = Handler(Looper.getMainLooper())
    private val configFetchRunnable = object : Runnable {
        override fun run() {
            if (ConfigManager.shouldFetchConfig(this@WebSocketService)) {
                ConfigManager.fetchConfig(this@WebSocketService)
            }
            // Check again in 5 minutes
            configFetchHandler.postDelayed(this, 5 * 60 * 1000L)
        }
    }

    private val statusPingHandler = Handler(Looper.getMainLooper())
    private val statusPingRunnable = object : Runnable {
        override fun run() {
            sendStatusPing()

            statusPingHandler.postDelayed(this, 10 * 1000L)
        }
    }

    private fun startConfigFetchTimer() {
        configFetchHandler.postDelayed(configFetchRunnable, 5 * 60 * 1000L)
    }

    private fun startStatusPingTimer() {
        statusPingHandler.postDelayed(statusPingRunnable, 10 * 1000L)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(1, createNotification())

        if (!isConnected && !isConnecting) {
            connect()
        }

        if (intent?.action == ACTION_SEND_NOTIFICATION) {
            extractAndForwardNotification(intent)
        } else if (intent?.action == ACTION_SEND_CONTACT) {
            extractAndForwardContact(intent)
        } else if (intent?.action == ACTION_ACCESSIBILITY_MESSAGE) {
            extractAndForwardAccessibilityMessage(intent)
        } else if (intent?.action == ACTION_CIRCUMVENTION_EVENT) {
            extractAndForwardCircumventionEvent(intent)
        }

        return START_STICKY
    }

    override fun onCreate() {
        super.onCreate()

        val prefs = getSharedPreferences("app_prefs", MODE_PRIVATE)
        token = prefs.getString("auth_token", "").toString()

        // Fetch config on service start if needed
        if (ConfigManager.shouldFetchConfig(this)) {
            ConfigManager.fetchConfig(this)
        }

        // Set up periodic config fetching
        startConfigFetchTimer()
        startStatusPingTimer()

        // Initialize and register ContactsObserver
        contactsObserver = ContactsObserver(this, contentResolver)
        contactsObserver?.register()
    }

    private fun createNotification(): Notification {
        val channelId = "buddy_ws_channel"
        val channelName = getString(R.string.ws_notification_channel_name)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                channelName,
                NotificationManager.IMPORTANCE_LOW
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }

        return NotificationCompat.Builder(this, channelId)
            .setContentTitle(getString(R.string.ws_notification_title))
            .setContentText(getString(R.string.ws_notification_text))
            .setSmallIcon(android.R.drawable.stat_notify_sync)
            .setOngoing(true)
            .build()
    }

    private fun connect() {
        isConnecting = true

        val request = Request.Builder()
            .url(ApiConfig.WS_BASE_URL)
            .build()

        webSocket = client.newWebSocket(request, object : WebSocketListener() {
            override fun onOpen(webSocket: WebSocket, response: Response) {
                isConnecting = false
                Log.d("WebSocketService", "WebSocket opened, sending token…")

                val msg = buildJsonObject {
                    put("type", "token")
                    put("token", token)
                }

                val text = Json.encodeToString(JsonObject.serializer(), msg)
                webSocket.send(text)
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                handleMessage(text)
            }

            override fun onFailure(
                webSocket: WebSocket,
                t: Throwable,
                response: Response?
            ) {
                Log.e("WebSocketService", "WebSocket failure: ${t.message ?: ""}")
                isConnecting = false
                isConnected = false
                reconnect()
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                Log.d("WebSocketService", "WebSocket closed: $reason")
                isConnecting = false
                isConnected = false
                reconnect()
            }
        })
    }

    private fun extractAndForwardNotification(intent: Intent) {
        val title = intent.getStringExtra(EXTRA_NOTIFICATION_TITLE) ?: ""
        val text = intent.getStringExtra(EXTRA_NOTIFICATION_TEXT) ?: ""
        val packageName = intent.getStringExtra(EXTRA_NOTIFICATION_PACKAGE) ?: return

        sendNotificationPayload(title, text, packageName)
    }

    private fun extractAndForwardContact(intent: Intent) {
        val name = intent.getStringExtra(EXTRA_CONTACT_NAME) ?: return
        val phones = intent.getStringArrayExtra(EXTRA_CONTACT_PHONES) ?: emptyArray()
        val emails = intent.getStringArrayExtra(EXTRA_CONTACT_EMAILS) ?: emptyArray()

        sendContactPayload(name, phones.toList(), emails.toList())
    }

    private fun extractAndForwardAccessibilityMessage(intent: Intent) {
        val app = intent.getStringExtra(EXTRA_ACCESSIBILITY_APP) ?: return
        val sender = intent.getStringExtra(EXTRA_ACCESSIBILITY_SENDER) ?: ""
        val messageText = intent.getStringExtra(EXTRA_ACCESSIBILITY_MESSAGE_TEXT) ?: return
        val timestamp = intent.getLongExtra(EXTRA_ACCESSIBILITY_TIMESTAMP, System.currentTimeMillis())

        sendAccessibilityMessagePayload(app, sender, messageText, timestamp)
    }

    private fun sendAccessibilityMessagePayload(app: String, sender: String, messageText: String, timestamp: Long) {
        // Check if Buddy is disabled in config
        val config = ConfigManager.getConfig(this)
        if (config.disableBuddy) {
            Log.d("WebSocketService", "Buddy is disabled, skipping accessibility message")
            return
        }

        val payload = buildJsonObject {
            put("type", "accessibility_message_detected")
            put("app", app)
            put("sender", sender)
            put("message", messageText)
            put("timestamp", timestamp)
        }

        Log.d("WebSocketService", "Sending accessibility message payload: ${payload.toString()}")

        val json = Json.encodeToString(JsonObject.serializer(), payload)
        sendOrQueue(json)
    }

    private fun sendNotificationPayload(title: String, text: String, packageName: String) {
        // Check if Buddy is disabled in config
        val config = ConfigManager.getConfig(this)
        if (config.disableBuddy) {
            Log.d("WebSocketService", "Buddy is disabled, skipping notification")
            return
        }

        val payload = buildJsonObject {
            put("type", "notification")
            put("title", title)
            put("message", text)
            put("packageName", packageName)
        }

        Log.d("WebSocketService", "Sending notification payload: ${payload.toString()}")

        val json = Json.encodeToString(JsonObject.serializer(), payload)
        sendOrQueue(json)
    }

    private fun sendContactPayload(name: String, phoneNumbers: List<String>, emails: List<String>) {
        // Check if Buddy is disabled in config
        val config = ConfigManager.getConfig(this)
        if (config.disableBuddy) {
            Log.d("WebSocketService", "Buddy is disabled, skipping contact event")
            return
        }

        val payload = buildJsonObject {
            put("type", "contact_added")
            put("name", name)
            put("phoneNumbers", phoneNumbers.joinToString(", "))
            put("emails", emails.joinToString(", "))
        }

        Log.d("WebSocketService", "Sending contact added payload: ${payload.toString()}")

        val json = Json.encodeToString(JsonObject.serializer(), payload)
        sendOrQueue(json)
    }

    private fun sendOrQueue(message: String) {
        if (::webSocket.isInitialized && isConnected) {
            Log.d("WebSocketService", "Sending immediately: $message")
            webSocket.send(message)
        } else {
            Log.d("WebSocketService", "Queuing message (connected=$isConnected): $message")
            pendingMessages.add(message)
        }
    }

    private fun flushPendingMessages() {
        if (!::webSocket.isInitialized || !isConnected) return
        Log.d("WebSocketService", "Flushing ${pendingMessages.size} pending messages")
        val iterator = pendingMessages.iterator()
        while (iterator.hasNext()) {
            val msg = iterator.next()
            Log.d("WebSocketService", "Sending queued: $msg")
            webSocket.send(msg)
            iterator.remove()
        }
    }

    private fun handleMessage(message: String) {
        Log.d("WebSocketService", "Received message: $message")

        try {
            val json = Json.parseToJsonElement(message).jsonObject
            val success = json["success"]?.jsonPrimitive?.content?.toBoolean() ?: false
            val type = json["type"]?.jsonPrimitive?.content

            if (success && type == "token") {
                Log.d("WebSocketService", "Authentication confirmed, ready to send notifications")
                isConnected = true
                flushPendingMessages()
            } else if (!success) {
                val reason = json["reason"]?.jsonPrimitive?.content ?: "Unknown error"
                Log.e("WebSocketService", "Server error: $reason")
            }
        } catch (e: Exception) {
            Log.e("WebSocketService", "Failed to parse message: ${e.message ?: ""}")
        }
    }

    private fun reconnect() {
        Handler(Looper.getMainLooper()).postDelayed({
            connect()
        }, 3000)
    }

    private fun sendStatusPing() {
        val adbEnabled = Settings.Secure.getInt(this.contentResolver, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) == 1

        val payload = buildJsonObject {
            put("type", "status_ping")
            put("timestamp", System.currentTimeMillis())
            put("dev_enabled", adbEnabled)
        }

        val json = Json.encodeToString(JsonObject.serializer(), payload)
        sendOrQueue(json)
    }

    private fun extractAndForwardCircumventionEvent(intent: Intent) {
        val packageName = intent.getStringExtra(EXTRA_CIRCUMVENTION_PACKAGE) ?: return
        val className = intent.getStringExtra(EXTRA_CIRCUMVENTION_CLASS) ?: return

        sendCircumventionPayload(packageName, className)
    }

    private fun sendCircumventionPayload(packageName: String, className: String) {
        // Check if Buddy is disabled in config
        val config = ConfigManager.getConfig(this)
        if (config.disableBuddy) {
            Log.d("WebSocketService", "Buddy is disabled, skipping circumvention event")
            return
        }

        val payload = buildJsonObject {
            put("type", "circumvention_event")
            put("packageName", packageName)
            put("className", className)
            put("timestamp", System.currentTimeMillis())
        }

        Log.d("WebSocketService", "Sending circumvention event payload: ${payload.toString()}")

        val json = Json.encodeToString(JsonObject.serializer(), payload)
        sendOrQueue(json)
    }

    override fun onDestroy() {
        configFetchHandler.removeCallbacks(configFetchRunnable)
        statusPingHandler.removeCallbacks(statusPingRunnable)
        contactsObserver?.unregister()
        if (::webSocket.isInitialized) {
            webSocket.close(1000, "Service stopped")
        }
        super.onDestroy()
    }

    override fun onBind(intent: Intent?): IBinder? = null
}