package com.yama.client import android.Manifest import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Handler import android.os.Looper import android.util.Log import java.nio.CharBuffer import java.nio.charset.CharacterCodingException import java.nio.charset.Charset import java.nio.charset.CodingErrorAction /** * 远程交谈(COMMAND_CHAT)的 Android 会话层。 * * native 侧(android/.../cpp/ChatHandler.h + ChatThread)负责子连接与协议,这里只管界面: * - onNativeEvent 由 native 子线程回调,统一切到主线程再分发; * - 消息按 GBK 解码(协议是 CP936,与 Windows 客户端一致),发出去前严格编码, * emoji / GBK 表示不了的字符直接拒绝并提示,绝不静默变成 '?'; * - 聊天界面用 ControlService(无障碍)在后台拉起,没有无障碍时退一条通知, * 用户点开后由通知进入 ChatActivity —— 与升级安装框/卸载确认框同一条路。 */ object ChatSession { private const val TAG = "YAMA_CHAT" private const val CHANNEL_ID = "yama_chat" private const val NOTIF_ID = 104 data class Line(val mine: Boolean, val text: String) private val gate = Any() private val history = ArrayDeque() private var lineListener: ((Line) -> Unit)? = null private var stateListener: (() -> Unit)? = null private val main = Handler(Looper.getMainLooper()) private val gbk = Charset.forName("GBK") /** 服务端已绑定子连接(收到 COMMAND_NEXT_CHAT)且会话尚未结束 */ @Volatile var active = false private set /** ChatActivity 在前台:避免每条消息都 startActivity 打扰正在输入的用户 */ @Volatile var uiVisible = false /** native 回调入口。kind: 1 = 已绑定,2 = 会话结束,3 = 一条 GBK 文本 */ @JvmStatic fun onNativeEvent(kind: Int, data: ByteArray?) { main.post { handle(kind, data) } } private fun handle(kind: Int, data: ByteArray?) { when (kind) { 1 -> { Log.i(TAG, "session opened") // 新会话:上一条会话的记录不带过来(Windows 客户端每次都是全新对话框)。 // 同一会话内关掉界面再打开时历史仍在,由 attach() 的注释描述。 synchronized(gate) { history.clear() } active = true notifyState() showUi() } 2 -> { // 一直没连上就结束(connect 失败)也会收到 2:从未打开过会话时不打扰用户 if (!active) { Log.i(TAG, "closed event without an open session, ignored") return } Log.i(TAG, "session closed") active = false // 界面收到 state 回调后会自己 finish();这里先清掉可见标志, // 免得服务端紧接着又开一个新会话时 showUi() 被旧窗口挡住不弹。 uiVisible = false notifyState() cancelNotification() } 3 -> { if (data == null || data.isEmpty()) return // 去尾随 NUL(Windows 客户端发送带 NUL,MFC 路径同样) val text = String(data, gbk).trimEnd('\u0000') if (text.isEmpty()) return active = true append(Line(false, text)) showUi() // 用户关掉窗口后再来消息 → 重新拉起(与 Windows SW_RESTORE 一致) } } } /** ChatActivity 打开时调用:注册监听并取回历史(在锁内拷贝,回调始终在主线程) */ fun attach(onLine: (Line) -> Unit, onState: () -> Unit): List = synchronized(gate) { lineListener = onLine stateListener = onState history.toList() } fun detach(onLine: (Line) -> Unit) = synchronized(gate) { if (lineListener === onLine) lineListener = null stateListener = null } /** * 发送一条文本。返回 false 表示没有会话、超出 4000 GBK 字节,或含 GBK 表示不了的字符 * (调用方据此提示,不要只说「发送失败」)。 */ fun send(text: String): Boolean { if (text.isEmpty() || !active) return false val encoder = gbk.newEncoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) val bytes = try { val bb = encoder.encode(CharBuffer.wrap(text)) ByteArray(bb.remaining()).also { bb.get(it) } } catch (e: CharacterCodingException) { Log.w(TAG, "send rejected: character not representable in GBK") return false } if (bytes.isEmpty() || bytes.size > 4000) return false if (!YamaBridge.nativeChatSend(bytes)) { Log.w(TAG, "send rejected by native (${bytes.size} bytes, no active sub-connection)") return false } append(Line(true, text)) return true } fun cancelNotification() { val ctx = CaptureService.instance ?: CaptureService.appContext ?: return val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return runCatching { nm.cancel(NOTIF_ID) } } private fun append(line: Line) { val cb = synchronized(gate) { history.addLast(line) while (history.size > 200) history.removeFirst() lineListener } cb?.invoke(line) } private fun notifyState() { val cb = synchronized(gate) { stateListener } cb?.invoke() } // ---------------------------------------------------------------- 拉起界面 private fun showUi() { if (uiVisible) return val ctx = CaptureService.instance ?: CaptureService.appContext ?: return val intent = Intent(ctx, ChatActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) val acc = ControlService.instance if (acc != null) { val ok = runCatching { acc.startActivity(intent) }.isSuccess if (ok) { Log.i(TAG, "chat UI opened via accessibility") return } Log.w(TAG, "accessibility startActivity failed, falling back to notification") } else { Log.w(TAG, "no accessibility, posting notification") } notifyUser(ctx) } private fun notifyUser(ctx: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ctx.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { Log.w(TAG, "notification skipped: POST_NOTIFICATIONS not granted") return } val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { nm.createNotificationChannel( NotificationChannel(CHANNEL_ID, "YAMA 远程交谈", NotificationManager.IMPORTANCE_HIGH)) } var flags = PendingIntent.FLAG_UPDATE_CURRENT if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) flags = flags or PendingIntent.FLAG_IMMUTABLE val pi = PendingIntent.getActivity(ctx, NOTIF_ID, Intent(ctx, ChatActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), flags) val b = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(ctx, CHANNEL_ID) else @Suppress("DEPRECATION") Notification.Builder(ctx) b.setSmallIcon(android.R.drawable.sym_action_chat) .setContentTitle("YAMA 远程交谈") .setContentText("有人在与你交谈,点按查看并回复。") .setAutoCancel(true) .setContentIntent(pi) runCatching { nm.notify(NOTIF_ID, b.build()) } } }