leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | package com.androidremote.companion |
| 2 | |
| 3 | import android.content.BroadcastReceiver |
| 4 | import android.content.ClipData |
| 5 | import android.content.ClipboardManager |
| 6 | import android.content.ContentProvider |
| 7 | import android.content.ContentValues |
| 8 | import android.content.Context |
| 9 | import android.content.Intent |
| 10 | import android.database.Cursor |
| 11 | import android.database.MatrixCursor |
| 12 | import android.net.Uri |
| 13 | import android.os.ParcelFileDescriptor |
| 14 | import android.provider.OpenableColumns |
| 15 | import android.util.Log |
| 16 | import org.json.JSONObject |
| 17 | import java.io.ByteArrayOutputStream |
| 18 | import java.io.DataInputStream |
| 19 | import java.io.File |
| 20 | import java.io.FileNotFoundException |
| 21 | import java.io.InputStream |
| 22 | import java.io.OutputStreamWriter |
| 23 | import java.net.InetSocketAddress |
| 24 | import java.net.Socket |
| 25 | |
| 26 | /** |
| 27 | * 호스트 이미지를 기기 클립보드에 넣는다 (기획서 3.2 이미지 확장). |
| 28 | * |
| 29 | * shell 데몬은 다른 앱이 읽을 수 있는 content URI를 만들 수 없으므로, 데몬이 이 수신기를 깨우면 |
| 30 | * 앱이 데몬에서 이미지를 받아 캐시에 저장하고 [ClipProvider] URI로 클립보드에 넣는다. 붙여넣는 앱은 |
| 31 | * 클립보드 서비스가 부여한 URI 권한으로 읽는다. 수신기는 DUMP 권한으로 보호해 shell만 보낼 수 있다. |
| 32 | */ |
| 33 | class ClipImageReceiver : BroadcastReceiver() { |
| 34 | override fun onReceive(context: Context, intent: Intent) { |
| 35 | val id = intent.getIntExtra("id", -1) |
| 36 | DaemonEndpoint.save(context, intent.getStringExtra("token"), intent.getIntExtra("port", 0)) |
| 37 | val app = context.applicationContext |
| 38 | val pending = goAsync() |
| 39 | Thread({ |
| 40 | try { |
| 41 | fetchAndSet(app, id) |
| 42 | } catch (e: Exception) { |
| 43 | Log.w(TAG, "이미지 클립보드 실패: $e") |
| 44 | } finally { |
| 45 | pending.finish() |
| 46 | } |
| 47 | }, "clip-image").start() |
| 48 | } |
| 49 | |
| 50 | private fun fetchAndSet(context: Context, id: Int) { |
| 51 | val (token, port) = DaemonEndpoint.load(context) ?: throw IllegalStateException("데몬 토큰 없음") |
| 52 | Socket().use { s -> |
| 53 | s.connect(InetSocketAddress("127.0.0.1", port), 1000) |
| 54 | s.soTimeout = 8000 |
| 55 | val out = OutputStreamWriter(s.outputStream, Charsets.UTF_8) |
| 56 | fun send(obj: JSONObject) { |
| 57 | out.write(obj.toString()) |
| 58 | out.write("\n") |
| 59 | out.flush() |
| 60 | } |
| 61 | send(JSONObject().put("type", "hello").put("token", token)) |
| 62 | send(JSONObject().put("type", "clip_image_get").put("id", id)) |
| 63 | val input = DataInputStream(s.getInputStream().buffered()) |
| 64 | // 데몬은 접속하자마자 상태 메시지를 보내므로 원하는 응답이 올 때까지 줄을 건너뛴다. |
| 65 | var header: JSONObject |
| 66 | while (true) { |
| 67 | header = JSONObject(readLine(input) ?: throw IllegalStateException("데몬 연결 끊김")) |
| 68 | if (header.optString("type") == "clip_image" && header.optInt("id") == id) break |
| 69 | } |
| 70 | val size = header.optInt("size", -1) |
| 71 | var ok = false |
| 72 | if (size > 0) { |
| 73 | val data = ByteArray(size).also { input.readFully(it) } |
| 74 | val ext = if (header.optString("mime") == "image/jpeg") "jpg" else "png" |
| 75 | val uri = ClipProvider.store(context, id, ext, data) |
| 76 | val cm = context.getSystemService(ClipboardManager::class.java) |
| 77 | cm.setPrimaryClip(ClipData.newUri(context.contentResolver, "Android Remote", uri)) |
| 78 | ok = true |
| 79 | Log.i(TAG, "호스트 이미지를 클립보드에 넣음: $uri ($size 바이트)") |
| 80 | } |
| 81 | send(JSONObject().put("type", "clip_image_set").put("id", id).put("ok", ok)) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /** UTF-8 한 줄을 바이트 단위로 읽는다. 뒤따르는 이미지 바이트를 버퍼로 미리 삼키지 않기 위해서다. */ |
| 86 | private fun readLine(input: InputStream): String? { |
| 87 | val buf = ByteArrayOutputStream() |
| 88 | while (true) { |
| 89 | val b = input.read() |
| 90 | if (b < 0) return if (buf.size() == 0) null else buf.toString(Charsets.UTF_8.name()) |
| 91 | if (b == '\n'.code) return buf.toString(Charsets.UTF_8.name()) |
| 92 | buf.write(b) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | companion object { |
| 97 | private const val TAG = "AndroidRemote" |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * 클립보드 이미지 파일 제공자. 외부에 공개하지 않고(exported=false), 클립보드 서비스가 붙여넣는 |
| 103 | * 앱에 부여하는 URI 권한으로만 읽힌다. 마지막 몇 개만 남기고 오래된 파일은 지운다. |
| 104 | */ |
| 105 | class ClipProvider : ContentProvider() { |
| 106 | override fun onCreate() = true |
| 107 | |
| 108 | private fun fileOf(uri: Uri): File { |
| 109 | val ctx = context ?: throw FileNotFoundException() |
| 110 | val name = uri.lastPathSegment ?: throw FileNotFoundException() |
| 111 | if (name.contains('/') || name.startsWith(".")) throw FileNotFoundException() |
| 112 | val f = File(dir(ctx), name) |
| 113 | if (!f.isFile) throw FileNotFoundException(name) |
| 114 | return f |
| 115 | } |
| 116 | |
| 117 | override fun getType(uri: Uri): String = |
| 118 | if (uri.lastPathSegment?.endsWith(".jpg") == true) "image/jpeg" else "image/png" |
| 119 | |
| 120 | override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor { |
| 121 | if (mode != "r") throw SecurityException("읽기 전용") |
| 122 | return ParcelFileDescriptor.open(fileOf(uri), ParcelFileDescriptor.MODE_READ_ONLY) |
| 123 | } |
| 124 | |
| 125 | override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor { |
| 126 | val f = fileOf(uri) |
| 127 | val cols = projection ?: arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE) |
| 128 | val row = cols.map { |
| 129 | when (it) { |
| 130 | OpenableColumns.DISPLAY_NAME -> f.name |
| 131 | OpenableColumns.SIZE -> f.length() |
| 132 | else -> null |
| 133 | } |
| 134 | } |
| 135 | return MatrixCursor(cols, 1).apply { addRow(row) } |
| 136 | } |
| 137 | |
| 138 | override fun insert(uri: Uri, values: ContentValues?): Uri? = null |
| 139 | override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?) = 0 |
| 140 | override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?) = 0 |
| 141 | |
| 142 | companion object { |
| 143 | const val AUTHORITY = "com.androidremote.clip" |
| 144 | private const val KEEP = 3 |
| 145 | |
| 146 | private fun dir(context: Context) = File(context.cacheDir, "clip").apply { mkdirs() } |
| 147 | |
| 148 | fun store(context: Context, id: Int, ext: String, data: ByteArray): Uri { |
| 149 | val d = dir(context) |
| 150 | val name = "clip-${System.currentTimeMillis()}-$id.$ext" |
| 151 | File(d, name).writeBytes(data) |
| 152 | d.listFiles()?.sortedByDescending { it.lastModified() }?.drop(KEEP)?.forEach { it.delete() } |
| 153 | return Uri.Builder().scheme("content").authority(AUTHORITY).appendPath(name).build() |
| 154 | } |
| 155 | } |
| 156 | } |