feat(receiver): 授权开关与按需投屏,新增 LocalSend 风格文件服务
- 新增 Prefs 持久化 + BootReceiver 开机自启,主开关打开后进入应用/开机自动准备待命 - Service 拆为待命/投屏两阶段:待命只维持广播与控制通道,不建编码器、不创建 VirtualDisplay - 新增控制帧 msgType=8 Mirror:主控端请求投屏,被控端弹窗确认并校验屏幕录制权限后才开流 - 新增 MirrorRequestActivity 透明确认页(通知兜底 + 30s 超时自动拒绝) - 投屏按本机真实分辨率(不强制横屏)适配,旋转/分辨率变化自动重建采集 - 新增 LocalSend 风格 HTTP 文件服务(53317,含 info/browse/download/upload/mirror),目录做根路径越权校验,主界面提供存储与通知权限申请 - 控制通道 msgType=7 增加 op=list 目录浏览;Rust/Dart 同步支持投屏请求并加工具栏按钮
This commit is contained in:
1 parent
3feddb3434
commit
f87ef59d98
23 files changed
+1840
-274
No files matched your search
@@ -157,6 +157,7 @@ sig=<信令服务器URL,可选>
|
|||||||
struct ControlFrameHeader {
|
struct ControlFrameHeader {
|
||||||
u8 version; // 当前 = 1
|
u8 version; // 当前 = 1
|
||||||
u8 msg_type; // 0=touch 1=mouse 2=key 3=wheel 4=clipboard 5=ping 6=pong
|
u8 msg_type; // 0=touch 1=mouse 2=key 3=wheel 4=clipboard 5=ping 6=pong
|
||||||
|
// 7=file(JSON 子协议) 8=mirror(投屏请求/应答)
|
||||||
u16 sequence; // 递增序号,用于去重/重传
|
u16 sequence; // 递增序号,用于去重/重传
|
||||||
u32 payload_len; // 负载长度(不包括头部)
|
u32 payload_len; // 负载长度(不包括头部)
|
||||||
};
|
};
|
||||||
@@ -190,6 +191,12 @@ struct ClipboardEvent {
|
|||||||
u32 length;
|
u32 length;
|
||||||
u8 data[length]; // UTF-8 文本
|
u8 data[length]; // UTF-8 文本
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 投屏请求/应答(msg_type = 8):被控端默认只待命,收到请求后弹窗确认才开流
|
||||||
|
struct MirrorEvent {
|
||||||
|
u8 action; // 0=request 1=stop 2=granted 3=denied 4=stopped 5=error
|
||||||
|
u8 message[]; // 可选,UTF-8 原因说明(denied/error 时)
|
||||||
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 4.4.2 序列化/反序列化抽象接口
|
#### 4.4.2 序列化/反序列化抽象接口
|
||||||
@@ -381,6 +388,26 @@ GET /file/progress ?sessionId= (SSE 或轮询)
|
|||||||
|
|
||||||
单向兼容,不反向依赖。
|
单向兼容,不反向依赖。
|
||||||
|
|
||||||
|
### 6.6 已落地的被控端实现(Android)
|
||||||
|
|
||||||
|
被控端内置一个 LocalSend 风格 HTTP 服务(默认 `53317`,被占用时顺延 `53318~53320`),
|
||||||
|
无需主控端即可用浏览器/curl 验证:
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/localsend/v2/info 设备信息(无需令牌)
|
||||||
|
POST /api/localsend/v2/register 注册握手(无需令牌)
|
||||||
|
GET /browse?path=&token= 浏览目录 → {path,parent,roots,entries[]}
|
||||||
|
GET /download?path=&token= 下载文件
|
||||||
|
POST /api/localsend/v2/upload?path=&name=&token= 接收文件
|
||||||
|
POST /mirror/request?token= 触发一次投屏确认(便于无主控端时验证)
|
||||||
|
```
|
||||||
|
|
||||||
|
- 除 info/register 外均需 `token`(query 或 `X-Lancast-Token` 头),令牌显示在被控端主界面。
|
||||||
|
- 路径做 `canonicalFile` 校验,必须落在允许的根目录内,杜绝 `../` 穿越。
|
||||||
|
- Android 11+ 需「所有文件访问权限」才能浏览 `/storage/emulated/0`,否则回落到应用私有的
|
||||||
|
`Android/data/<pkg>/files` 目录;应用内提供权限申请入口。
|
||||||
|
- 同一条控制通道也支持 `msg_type=7` + `{"op":"list","path":"..."}` 的目录浏览。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. 安全模型
|
## 7. 安全模型
|
||||||
|
|||||||
@@ -3,9 +3,26 @@
|
|||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
|
||||||
|
<!-- 文件服务:浏览/读写 Android 目录所需的存储权限 -->
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||||
|
android:maxSdkVersion="32" />
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||||
|
android:maxSdkVersion="28" />
|
||||||
|
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||||
|
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
|
||||||
|
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
|
||||||
|
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
|
||||||
|
|
||||||
|
<!-- 后台弹窗确认投屏请求(可选,授予后主控端请求时可直接弹框) -->
|
||||||
|
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:allowBackup="false"
|
android:allowBackup="false"
|
||||||
@@ -22,12 +39,30 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
|
<!-- 投屏确认页:透明对话框,独立任务栈避免影响主界面 -->
|
||||||
|
<activity
|
||||||
|
android:name=".MirrorRequestActivity"
|
||||||
|
android:excludeFromRecents="true"
|
||||||
|
android:exported="false"
|
||||||
|
android:taskAffinity="com.ttstd.lancast.receiver.request"
|
||||||
|
android:theme="@style/Theme.Lancast.Request" />
|
||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".MediaProjectionService"
|
android:name=".MediaProjectionService"
|
||||||
android:enabled="true"
|
android:enabled="true"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="mediaProjection" />
|
android:foregroundServiceType="mediaProjection" />
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".BootReceiver"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
|
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".input.LancastAccessibilityService"
|
android:name=".input.LancastAccessibilityService"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.ttstd.lancast.receiver
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.util.Log
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开机自启。
|
||||||
|
*
|
||||||
|
* 主开关打开时,开机后把服务拉起来待命并尽量拉起界面完成屏幕录制授权。
|
||||||
|
*
|
||||||
|
* 注意:Android 10+ 限制后台启动 Activity,Android 14+ 还限制从 BOOT_COMPLETED 启动
|
||||||
|
* `mediaProjection` 类型前台服务,所以这里每一步都做失败兜底 —— 被系统拦截时用户下次打开
|
||||||
|
* 应用仍会自动进入待命([MainActivity.onCreate] 里的 autoGrant 分支)。
|
||||||
|
*/
|
||||||
|
class BootReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "BootReceiver"
|
||||||
|
private const val ACTION_QUICKBOOT = "android.intent.action.QUICKBOOT_POWERON"
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent?) {
|
||||||
|
val action = intent?.action ?: return
|
||||||
|
if (action != Intent.ACTION_BOOT_COMPLETED && action != ACTION_QUICKBOOT) return
|
||||||
|
if (!Prefs.autoGrant(context)) {
|
||||||
|
Log.i(TAG, "开机自启已关闭,跳过")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.i(TAG, "开机自启:尝试进入待命")
|
||||||
|
// 先尝试拉起界面(系统签名变体或已授予后台弹出权限时可用),同时拉起待命服务。
|
||||||
|
try {
|
||||||
|
context.startActivity(
|
||||||
|
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||||
|
)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "开机拉起界面被系统拦截: ${error.message}")
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
MediaProjectionService.start(context)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "开机启动待命服务失败: ${error.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +1,31 @@
|
|||||||
package com.ttstd.lancast.receiver
|
package com.ttstd.lancast.receiver
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
import android.app.Activity
|
import android.app.Activity
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
import android.media.projection.MediaProjectionManager
|
import android.media.projection.MediaProjectionManager
|
||||||
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
import android.widget.Button
|
import android.widget.Button
|
||||||
import android.widget.LinearLayout
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.ScrollView
|
||||||
|
import android.widget.Switch
|
||||||
import android.widget.TextView
|
import android.widget.TextView
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
||||||
|
import com.ttstd.lancast.receiver.file.StorageAccess
|
||||||
import com.ttstd.lancast.receiver.session.PairingCode
|
import com.ttstd.lancast.receiver.session.PairingCode
|
||||||
import java.net.NetworkInterface
|
import java.net.NetworkInterface
|
||||||
|
|
||||||
class MainActivity : Activity() {
|
class MainActivity : Activity() {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val REQUEST_CAPTURE = 1001
|
private const val REQUEST_CAPTURE = 1001
|
||||||
|
private const val REQUEST_STORAGE = 1002
|
||||||
|
private const val REQUEST_NOTIFICATIONS = 1003
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 调试用:`adb shell am start -n com.ttstd.lancast.receiver/.MainActivity -e host 10.0.2.2`
|
* 调试用:`adb shell am start -n com.ttstd.lancast.receiver/.MainActivity -e host 10.0.2.2`
|
||||||
@@ -28,40 +37,188 @@ class MainActivity : Activity() {
|
|||||||
private lateinit var status: TextView
|
private lateinit var status: TextView
|
||||||
private lateinit var endpoint: TextView
|
private lateinit var endpoint: TextView
|
||||||
private lateinit var pairing: TextView
|
private lateinit var pairing: TextView
|
||||||
|
private lateinit var fileInfo: TextView
|
||||||
|
private lateinit var storageInfo: TextView
|
||||||
|
private lateinit var autoSwitch: Switch
|
||||||
|
private lateinit var confirmSwitch: Switch
|
||||||
|
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
private var hostOverride: String = ""
|
private var hostOverride: String = ""
|
||||||
|
private var authRequested = false
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
hostOverride = intent?.getStringExtra(EXTRA_HOST)?.trim().orEmpty()
|
hostOverride = intent?.getStringExtra(EXTRA_HOST)?.trim().orEmpty()
|
||||||
|
|
||||||
status = TextView(this).apply {
|
status = TextView(this).apply { textSize = 18f }
|
||||||
textSize = 18f
|
endpoint = TextView(this).apply { textSize = 13f }
|
||||||
text = "状态:未开始"
|
pairing = TextView(this).apply { textSize = 13f }
|
||||||
}
|
fileInfo = TextView(this).apply { textSize = 13f }
|
||||||
endpoint = TextView(this).apply {
|
storageInfo = TextView(this).apply { textSize = 12f }
|
||||||
textSize = 13f
|
|
||||||
text = "正在获取本机地址…"
|
|
||||||
}
|
|
||||||
pairing = TextView(this).apply {
|
|
||||||
textSize = 13f
|
|
||||||
text = "配对码:生成中..."
|
|
||||||
}
|
|
||||||
val start = Button(this).apply { text = "授权并开始投屏" }
|
|
||||||
val stop = Button(this).apply { text = "停止" }
|
|
||||||
|
|
||||||
setContentView(LinearLayout(this).apply {
|
autoSwitch = Switch(this).apply {
|
||||||
|
text = "允许远控(开机/进入应用自动准备)"
|
||||||
|
textSize = 14f
|
||||||
|
isChecked = Prefs.autoGrant(this@MainActivity)
|
||||||
|
setOnCheckedChangeListener { _, checked ->
|
||||||
|
Prefs.setAutoGrant(this@MainActivity, checked)
|
||||||
|
if (checked) {
|
||||||
|
startStandby()
|
||||||
|
autoAuthorize()
|
||||||
|
} else {
|
||||||
|
MediaProjectionService.stop(this@MainActivity)
|
||||||
|
}
|
||||||
|
refreshStatus
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
confirmSwitch = Switch(this).apply {
|
||||||
|
text = "主控端请求投屏时弹窗确认"
|
||||||
|
textSize = 14f
|
||||||
|
isChecked = Prefs.mirrorConfirm(this@MainActivity)
|
||||||
|
setOnCheckedChangeListener { _, checked ->
|
||||||
|
Prefs.setMirrorConfirm(this@MainActivity, checked)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val authorize = Button(this).apply {
|
||||||
|
text = "授权屏幕录制(仅待命,不投屏)"
|
||||||
|
setOnClickListener { startCaptureConsent() }
|
||||||
|
}
|
||||||
|
val startButton = Button(this).apply {
|
||||||
|
text = "启动待命服务"
|
||||||
|
setOnClickListener { startStandby() }
|
||||||
|
}
|
||||||
|
val storageButton = Button(this).apply {
|
||||||
|
text = "授予文件访问权限"
|
||||||
|
setOnClickListener { requestStorageAccess() }
|
||||||
|
}
|
||||||
|
val stop = Button(this).apply {
|
||||||
|
text = "停止"
|
||||||
|
setOnClickListener {
|
||||||
|
MediaProjectionService.stop(this@MainActivity)
|
||||||
|
status.text = "状态:已停止"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val content = LinearLayout(this).apply {
|
||||||
orientation = LinearLayout.VERTICAL
|
orientation = LinearLayout.VERTICAL
|
||||||
setPadding(48, 64, 48, 48)
|
setPadding(48, 64, 48, 64)
|
||||||
addView(status)
|
addView(status)
|
||||||
addView(endpoint)
|
addView(endpoint)
|
||||||
addView(pairing)
|
addView(pairing)
|
||||||
addView(start)
|
addView(autoSwitch)
|
||||||
|
addView(confirmSwitch)
|
||||||
|
addView(authorize)
|
||||||
|
addView(startButton)
|
||||||
|
addView(storageInfo)
|
||||||
|
addView(storageButton)
|
||||||
|
addView(fileInfo)
|
||||||
addView(stop)
|
addView(stop)
|
||||||
})
|
}
|
||||||
|
setContentView(ScrollView(this).apply { addView(content) })
|
||||||
|
|
||||||
|
requestNotificationPermission()
|
||||||
|
|
||||||
|
// 开关已打开时,进入应用即自动准备(服务待命 + 预授权屏幕录制)。
|
||||||
|
if (Prefs.autoGrant(this)) {
|
||||||
|
startStandby()
|
||||||
|
}
|
||||||
|
refreshLocalInfo()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
handler.post(refreshStatus)
|
||||||
|
if (Prefs.autoGrant(this) && !MediaProjectionService.hasProjection && !authRequested) {
|
||||||
|
autoAuthorize()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
handler.removeCallbacks(refreshStatus)
|
||||||
|
super.onPause()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 动作
|
||||||
|
|
||||||
|
private fun startStandby() {
|
||||||
|
MediaProjectionService.start(this, hostOverride, "")
|
||||||
|
status.text = "状态:正在进入待命…"
|
||||||
|
handler.postDelayed({ refreshStatus }, 300)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 进入应用/开机后的自动授权:只申请屏幕录制凭证,不创建 VirtualDisplay。 */
|
||||||
|
private fun autoAuthorize() {
|
||||||
|
if (authRequested || MediaProjectionService.hasProjection) return
|
||||||
|
authRequested = true
|
||||||
|
startCaptureConsent()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startCaptureConsent() {
|
||||||
|
if (MediaProjectionService.hasProjection) {
|
||||||
|
Toast.makeText(this, "已持有屏幕录制授权", Toast.LENGTH_SHORT).show()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val manager = getSystemService(MediaProjectionManager::class.java)
|
||||||
|
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun requestStorageAccess() {
|
||||||
|
if (StorageAccess.canBrowseAll(this)) {
|
||||||
|
Toast.makeText(this, "已具备完整文件访问权限", Toast.LENGTH_SHORT).show()
|
||||||
|
refreshStatus
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val settings = StorageAccess.allFilesSettingsIntent(this)
|
||||||
|
if (settings != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
Toast.makeText(this, "请在设置中允许「所有文件访问」", Toast.LENGTH_LONG).show()
|
||||||
|
runCatching { startActivity(settings) }
|
||||||
|
.onFailure { requestPermissions(StorageAccess.runtimePermissions(), REQUEST_STORAGE) }
|
||||||
|
} else {
|
||||||
|
requestPermissions(StorageAccess.runtimePermissions(), REQUEST_STORAGE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun requestNotificationPermission() {
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
|
||||||
|
if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) return
|
||||||
|
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATIONS)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||||
|
super.onActivityResult(requestCode, resultCode, data)
|
||||||
|
if (requestCode != REQUEST_CAPTURE) return
|
||||||
|
if (resultCode == RESULT_OK && data != null) {
|
||||||
|
// 只把凭证交给服务持有,不触发投屏。
|
||||||
|
MediaProjectionService.attachProjection(this, resultCode, data, mirrorAfter = false)
|
||||||
|
Toast.makeText(this, "已授权,服务保持待命(未投屏)", Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(this, "未授权屏幕录制,主控端请求时将再次询问", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
refreshStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onRequestPermissionsResult(
|
||||||
|
requestCode: Int,
|
||||||
|
permissions: Array<out String>,
|
||||||
|
grantResults: IntArray,
|
||||||
|
) {
|
||||||
|
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||||
|
if (requestCode == REQUEST_STORAGE || requestCode == REQUEST_NOTIFICATIONS) {
|
||||||
|
refreshStatus
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 状态
|
||||||
|
|
||||||
|
private fun refreshLocalInfo() {
|
||||||
Thread {
|
Thread {
|
||||||
val ip = try { localIp() } catch (_: Exception) { "" }
|
val ip = try {
|
||||||
|
localIp()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
""
|
||||||
|
}
|
||||||
val endpointText = if (ip.isEmpty()) {
|
val endpointText = if (ip.isEmpty()) {
|
||||||
"无法获取本机 IP,请检查网络"
|
"无法获取本机 IP,请检查网络"
|
||||||
} else {
|
} else {
|
||||||
@@ -77,55 +234,41 @@ class MainActivity : Activity() {
|
|||||||
pairing.text = pairingText
|
pairing.text = pairingText
|
||||||
}
|
}
|
||||||
}.start()
|
}.start()
|
||||||
|
|
||||||
start.setOnClickListener {
|
|
||||||
// 系统同一时刻只允许一路 MediaProjection:会话进行中再次授权会让正在采集的
|
|
||||||
// 那一路失效(non-current MediaProjection),必须等停止后再重新授权。
|
|
||||||
if (MediaProjectionService.isRunning) {
|
|
||||||
Toast.makeText(this, "投屏已在进行中,请先点「停止」", Toast.LENGTH_SHORT).show()
|
|
||||||
return@setOnClickListener
|
|
||||||
}
|
|
||||||
val manager = getSystemService(MediaProjectionManager::class.java)
|
|
||||||
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
|
|
||||||
}
|
|
||||||
stop.setOnClickListener {
|
|
||||||
MediaProjectionService.stop(this)
|
|
||||||
status.text = "状态:已停止"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onResume() {
|
/** 采集过程中持续刷新状态、文件服务地址与权限提示。 */
|
||||||
super.onResume()
|
|
||||||
handler.post(refreshStatus)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPause() {
|
|
||||||
handler.removeCallbacks(refreshStatus)
|
|
||||||
super.onPause()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 采集过程中持续刷新「等待主控端 / 已发现主控端」。 */
|
|
||||||
private val refreshStatus = object : Runnable {
|
private val refreshStatus = object : Runnable {
|
||||||
override fun run() {
|
override fun run() {
|
||||||
|
val state = MediaProjectionService.state
|
||||||
status.text = when {
|
status.text = when {
|
||||||
hostOverride.isNotEmpty() -> "状态:已指定主控端 $hostOverride"
|
state == MediaProjectionService.State.STREAMING -> "状态:投屏中"
|
||||||
!MediaProjectionService.isRunning -> "状态:未开始"
|
state == MediaProjectionService.State.STANDBY -> buildString {
|
||||||
MediaProjectionService.discoveredHost.isNotEmpty() ->
|
append("状态:待命(未投屏)")
|
||||||
"状态:采集中 · 已发现主控端 ${MediaProjectionService.discoveredHost}"
|
val host = MediaProjectionService.discoveredHost
|
||||||
else -> "状态:采集中 · 等待主控端连接(无需填写 IP)"
|
append(if (host.isNotEmpty()) " · 主控端 $host" else " · 等待主控端连接")
|
||||||
|
append(if (MediaProjectionService.hasProjection) " · 已获屏幕授权" else " · 未授权屏幕录制")
|
||||||
|
}
|
||||||
|
else -> "状态:未运行"
|
||||||
}
|
}
|
||||||
|
endpoint.text = if (hostOverride.isNotEmpty()) {
|
||||||
|
"已指定主控端:$hostOverride"
|
||||||
|
} else {
|
||||||
|
endpoint.text
|
||||||
|
}
|
||||||
|
|
||||||
|
val port = MediaProjectionService.filePort
|
||||||
|
val ip = runCatching { localIp() }.getOrDefault("")
|
||||||
|
fileInfo.text = when {
|
||||||
|
port <= 0 -> "文件服务:未启动(下方可手动启动待命服务)"
|
||||||
|
ip.isEmpty() -> "文件服务端口:$port"
|
||||||
|
else -> "文件服务:http://$ip:$port\n令牌:${Prefs.fileToken(this@MainActivity)}"
|
||||||
|
}
|
||||||
|
storageInfo.text = "文件访问:${StorageAccess.summary(this@MainActivity)}"
|
||||||
|
|
||||||
handler.postDelayed(this, 1000)
|
handler.postDelayed(this, 1000)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
|
||||||
super.onActivityResult(requestCode, resultCode, data)
|
|
||||||
if (requestCode != REQUEST_CAPTURE || resultCode != RESULT_OK || data == null) return
|
|
||||||
// host 留空即走 UDP 信标自动发现;信令服务器未配置时传空串。
|
|
||||||
MediaProjectionService.start(this, resultCode, data, hostOverride, "")
|
|
||||||
status.text = "状态:连接中..."
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun localIp(): String = NetworkInterface.getNetworkInterfaces().toList()
|
private fun localIp(): String = NetworkInterface.getNetworkInterfaces().toList()
|
||||||
.flatMap { it.inetAddresses.toList() }
|
.flatMap { it.inetAddresses.toList() }
|
||||||
.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
|
.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
|
||||||
|
|||||||
+418
-162
@@ -3,6 +3,7 @@ package com.ttstd.lancast.receiver
|
|||||||
import android.app.Notification
|
import android.app.Notification
|
||||||
import android.app.NotificationChannel
|
import android.app.NotificationChannel
|
||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
import android.app.Service
|
import android.app.Service
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
@@ -13,82 +14,169 @@ import android.os.Build
|
|||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
import android.util.DisplayMetrics
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import android.view.Display
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
|
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
||||||
|
import com.ttstd.lancast.receiver.file.FileHttpServer
|
||||||
|
import com.ttstd.lancast.receiver.protocol.MirrorAction
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 常驻前台服务。分两个阶段:
|
||||||
|
*
|
||||||
|
* - **待命(STANDBY)**:只广播设备信息、维持控制通道、提供文件服务;**不投屏**,不占用编码器。
|
||||||
|
* - **投屏(STREAMING)**:收到主控端 [MirrorAction.REQUEST] 且用户确认、权限校验通过后,
|
||||||
|
* 才建立编码器与 VirtualDisplay 开始推流。
|
||||||
|
*
|
||||||
|
* 屏幕录制授权(MediaProjection)只在需要投屏时才真正使用;即使提前拿到凭证也不会创建
|
||||||
|
* VirtualDisplay,因此「授权」不等于「投屏」。
|
||||||
|
*/
|
||||||
class MediaProjectionService : Service() {
|
class MediaProjectionService : Service() {
|
||||||
|
|
||||||
|
enum class State { IDLE, STANDBY, STREAMING }
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val TAG = "MediaProjectionService"
|
private const val TAG = "MediaProjectionService"
|
||||||
private const val CHANNEL_ID = "media_projection_service_channel"
|
private const val CHANNEL_SERVICE = "lancast_service_channel"
|
||||||
|
private const val CHANNEL_REQUEST = "lancast_request_channel"
|
||||||
private const val NOTIFICATION_ID = 1001
|
private const val NOTIFICATION_ID = 1001
|
||||||
|
private const val REQUEST_NOTIFICATION_ID = 1002
|
||||||
|
private const val REQUEST_TIMEOUT_MS = 30_000L
|
||||||
|
|
||||||
const val ACTION_START = "com.ttstd.lancast.receiver.action.START"
|
const val ACTION_START = "com.ttstd.lancast.receiver.action.START"
|
||||||
const val ACTION_STOP = "com.ttstd.lancast.receiver.action.STOP"
|
const val ACTION_STOP = "com.ttstd.lancast.receiver.action.STOP"
|
||||||
|
const val ACTION_ATTACH_PROJECTION = "com.ttstd.lancast.receiver.action.ATTACH_PROJECTION"
|
||||||
|
const val ACTION_MIRROR_START = "com.ttstd.lancast.receiver.action.MIRROR_START"
|
||||||
|
const val ACTION_MIRROR_DENY = "com.ttstd.lancast.receiver.action.MIRROR_DENY"
|
||||||
|
const val ACTION_MIRROR_STOP = "com.ttstd.lancast.receiver.action.MIRROR_STOP"
|
||||||
|
|
||||||
const val EXTRA_RESULT_CODE = "extra_result_code"
|
const val EXTRA_RESULT_CODE = "extra_result_code"
|
||||||
const val EXTRA_DATA = "extra_data"
|
const val EXTRA_DATA = "extra_data"
|
||||||
const val EXTRA_HOST = "extra_host"
|
const val EXTRA_HOST = "extra_host"
|
||||||
const val EXTRA_SIGNALING_URL = "extra_signaling_url"
|
const val EXTRA_SIGNALING_URL = "extra_signaling_url"
|
||||||
|
const val EXTRA_MIRROR_AFTER = "extra_mirror_after"
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var state: State = State.IDLE
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** 服务是否在运行(待命或投屏)。 */
|
||||||
@Volatile
|
@Volatile
|
||||||
var isRunning = false
|
var isRunning = false
|
||||||
private set
|
private set
|
||||||
|
|
||||||
|
/** 文件服务实际监听端口(0 表示未启动)。 */
|
||||||
|
@Volatile
|
||||||
|
var filePort = 0
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** 是否有待确认的投屏请求。 */
|
||||||
|
@Volatile
|
||||||
|
var pendingRequest = false
|
||||||
|
private set
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var projectionReady = false
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** 已持有可用的屏幕录制凭证(不代表正在投屏)。 */
|
||||||
|
val hasProjection: Boolean get() = projectionReady
|
||||||
|
|
||||||
|
val isStreaming: Boolean get() = state == State.STREAMING
|
||||||
|
|
||||||
/** 通过 UDP 信标自动发现的主控端地址(空串表示还没发现)。 */
|
/** 通过 UDP 信标自动发现的主控端地址(空串表示还没发现)。 */
|
||||||
val discoveredHost: String
|
val discoveredHost: String
|
||||||
get() = com.ttstd.lancast.receiver.discovery.HostBeacon.lastHost
|
get() = com.ttstd.lancast.receiver.discovery.HostBeacon.lastHost
|
||||||
|
|
||||||
fun start(context: Context, resultCode: Int, data: Intent, host: String, signalingUrl: String) {
|
/** 启动待命服务(不需要屏幕录制授权)。 */
|
||||||
|
fun start(context: Context, host: String = "", signalingUrl: String = "") {
|
||||||
val intent = Intent(context, MediaProjectionService::class.java).apply {
|
val intent = Intent(context, MediaProjectionService::class.java).apply {
|
||||||
action = ACTION_START
|
action = ACTION_START
|
||||||
putExtra(EXTRA_RESULT_CODE, resultCode)
|
|
||||||
putExtra(EXTRA_DATA, data)
|
|
||||||
putExtra(EXTRA_HOST, host)
|
putExtra(EXTRA_HOST, host)
|
||||||
putExtra(EXTRA_SIGNALING_URL, signalingUrl)
|
putExtra(EXTRA_SIGNALING_URL, signalingUrl)
|
||||||
}
|
}
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
context.startForegroundService(intent)
|
||||||
context.startForegroundService(intent)
|
|
||||||
} else {
|
|
||||||
context.startService(intent)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun stop(context: Context) {
|
fun stop(context: Context) {
|
||||||
val intent = Intent(context, MediaProjectionService::class.java).apply {
|
context.startForegroundService(Intent(context, MediaProjectionService::class.java).apply {
|
||||||
action = ACTION_STOP
|
action = ACTION_STOP
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把屏幕录制授权凭证交给服务;[mirrorAfter] 为 true 时立即开始投屏。 */
|
||||||
|
fun attachProjection(context: Context, resultCode: Int, data: Intent, mirrorAfter: Boolean) {
|
||||||
|
val intent = Intent(context, MediaProjectionService::class.java).apply {
|
||||||
|
action = ACTION_ATTACH_PROJECTION
|
||||||
|
putExtra(EXTRA_RESULT_CODE, resultCode)
|
||||||
|
putExtra(EXTRA_DATA, data)
|
||||||
|
putExtra(EXTRA_MIRROR_AFTER, mirrorAfter)
|
||||||
}
|
}
|
||||||
context.startService(intent)
|
context.startForegroundService(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startMirroring(context: Context) = sendAction(context, ACTION_MIRROR_START)
|
||||||
|
|
||||||
|
fun denyMirroring(context: Context) = sendAction(context, ACTION_MIRROR_DENY)
|
||||||
|
|
||||||
|
fun stopMirroring(context: Context) = sendAction(context, ACTION_MIRROR_STOP)
|
||||||
|
|
||||||
|
private fun sendAction(context: Context, action: String) {
|
||||||
|
context.startForegroundService(
|
||||||
|
Intent(context, MediaProjectionService::class.java).setAction(action),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var session: ReceiverSession? = null
|
private var session: ReceiverSession? = null
|
||||||
private var beacon: com.ttstd.lancast.receiver.discovery.HostBeacon? = null
|
private var beacon: HostBeacon? = null
|
||||||
|
private var fileServer: FileHttpServer? = null
|
||||||
|
|
||||||
/** 当前投影实例;必须持有引用,销毁时显式 stop(),否则会残留为「当前投影」。 */
|
|
||||||
private var projection: MediaProjection? = null
|
private var projection: MediaProjection? = null
|
||||||
private var projectionCallback: MediaProjection.Callback? = null
|
private var projectionCallback: MediaProjection.Callback? = null
|
||||||
|
|
||||||
/** 保护 [session] / [projection] / [generation] / [starting] 的状态锁。 */
|
private var hostOverride = ""
|
||||||
private val stateLock = Any()
|
private var signalingUrl = ""
|
||||||
|
|
||||||
/**
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
* 会话世代号,每次启动或销毁时递增。后台启动线程持旧世代号时不再操作投影,
|
private val requestTimeout = Runnable { denyPending("确认超时") }
|
||||||
* 避免上一路 MediaProjection 已被新一路顶掉后仍去 createVirtualDisplay。
|
|
||||||
*/
|
|
||||||
private var generation = 0
|
|
||||||
|
|
||||||
/** 正在创建投影 / 虚拟显示(尚未成功也未失败)。用于拦截重复启动请求。 */
|
/** 采集链路建立/销毁较重(MediaCodec + VirtualDisplay),放到单线程串行执行。 */
|
||||||
private var starting = false
|
private var worker = java.util.concurrent.Executors.newSingleThreadExecutor()
|
||||||
|
|
||||||
|
private fun execWorker(task: () -> Unit) {
|
||||||
|
try {
|
||||||
|
worker.execute(task)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// 线程池在上一轮 stop 时已关闭(服务实例被复用),重建一个。
|
||||||
|
worker = java.util.concurrent.Executors.newSingleThreadExecutor()
|
||||||
|
runCatching { worker.execute(task) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val notificationManager by lazy {
|
||||||
|
getSystemService(NotificationManager::class.java)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
createNotificationChannel()
|
createNotificationChannels()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
ensureForeground()
|
||||||
when (intent?.action) {
|
when (intent?.action) {
|
||||||
ACTION_START -> {
|
null, ACTION_START -> {
|
||||||
|
if (intent != null) {
|
||||||
|
hostOverride = intent.getStringExtra(EXTRA_HOST) ?: hostOverride
|
||||||
|
signalingUrl = intent.getStringExtra(EXTRA_SIGNALING_URL) ?: signalingUrl
|
||||||
|
}
|
||||||
|
ensureSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
ACTION_ATTACH_PROJECTION -> {
|
||||||
val resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0)
|
val resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0)
|
||||||
val data: Intent? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
val data: Intent? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
intent.getParcelableExtra(EXTRA_DATA, Intent::class.java)
|
intent.getParcelableExtra(EXTRA_DATA, Intent::class.java)
|
||||||
@@ -96,181 +184,253 @@ class MediaProjectionService : Service() {
|
|||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
intent.getParcelableExtra(EXTRA_DATA)
|
intent.getParcelableExtra(EXTRA_DATA)
|
||||||
}
|
}
|
||||||
val host = intent.getStringExtra(EXTRA_HOST) ?: ""
|
val mirrorAfter = intent.getBooleanExtra(EXTRA_MIRROR_AFTER, false)
|
||||||
val signalingUrl = intent.getStringExtra(EXTRA_SIGNALING_URL) ?: ""
|
|
||||||
|
|
||||||
if (resultCode != 0 && data != null) {
|
if (resultCode != 0 && data != null) {
|
||||||
startForegroundServiceWithNotification()
|
attachProjection(resultCode, data, mirrorAfter)
|
||||||
startProjectionSession(resultCode, data, host, signalingUrl)
|
|
||||||
} else {
|
} else {
|
||||||
stopSelf()
|
session?.notifyMirror(MirrorAction.ERROR, "屏幕录制授权失败")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ACTION_MIRROR_START -> beginMirroring()
|
||||||
|
|
||||||
|
ACTION_MIRROR_DENY -> denyPending("用户拒绝")
|
||||||
|
|
||||||
|
ACTION_MIRROR_STOP -> endMirroring(reply = true)
|
||||||
|
|
||||||
ACTION_STOP -> {
|
ACTION_STOP -> {
|
||||||
stopProjectionSession()
|
teardown()
|
||||||
stopSelf()
|
stopSelf()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
else -> ensureSession()
|
||||||
}
|
}
|
||||||
return START_NOT_STICKY
|
return START_NOT_STICKY
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startForegroundServiceWithNotification() {
|
// ------------------------------------------------------------------ 会话
|
||||||
val notification = createNotification()
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
/** 待命:建会话、广播、文件服务,全程不投屏。 */
|
||||||
startForeground(
|
private fun ensureSession() {
|
||||||
NOTIFICATION_ID,
|
if (session != null) return
|
||||||
notification,
|
val created = ReceiverSession(this, hostOverride, signalingUrl, "")
|
||||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
|
// 请求来自控制通道读线程,统一切回主线程处理。
|
||||||
)
|
created.onMirrorRequest = { action, message ->
|
||||||
} else {
|
handler.post { handleMirrorAction(action, message) }
|
||||||
startForeground(NOTIFICATION_ID, notification)
|
}
|
||||||
|
created.onStreamingLost = {
|
||||||
|
projectionReady = false
|
||||||
|
state = State.STANDBY
|
||||||
|
updateNotification()
|
||||||
|
}
|
||||||
|
session = created
|
||||||
|
created.start()
|
||||||
|
startBeacon()
|
||||||
|
startFileServer()
|
||||||
|
state = State.STANDBY
|
||||||
|
isRunning = true
|
||||||
|
updateNotification()
|
||||||
|
Log.i(TAG, "服务进入待命状态")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startBeacon() {
|
||||||
|
if (beacon != null) return
|
||||||
|
HostBeacon.resetHost()
|
||||||
|
val metrics = realMetrics()
|
||||||
|
beacon = HostBeacon(
|
||||||
|
HostBeacon.Offer(
|
||||||
|
id = UUID.randomUUID().toString(),
|
||||||
|
name = "Android Receiver",
|
||||||
|
model = Build.MODEL ?: "Android",
|
||||||
|
resolution = "${metrics.widthPixels}x${metrics.heightPixels}",
|
||||||
|
),
|
||||||
|
).also { it.start() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startFileServer() {
|
||||||
|
if (fileServer != null) return
|
||||||
|
if (!Prefs.fileServiceEnabled(this)) return
|
||||||
|
val server = FileHttpServer(
|
||||||
|
context = this,
|
||||||
|
tokenProvider = { Prefs.fileToken(this) },
|
||||||
|
onMirrorRequest = { requestConfirmation() },
|
||||||
|
)
|
||||||
|
val port = server.start()
|
||||||
|
if (port > 0) {
|
||||||
|
fileServer = server
|
||||||
|
filePort = port
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startProjectionSession(resultCode: Int, data: Intent, host: String, signalingUrl: String) {
|
// ------------------------------------------------------------------ 投屏
|
||||||
val gen = synchronized(stateLock) {
|
|
||||||
// 系统同一时刻只允许一路 MediaProjection 处于活动状态:再调一次 getMediaProjection
|
|
||||||
// 会立刻让上一路失效,其 createVirtualDisplay 便抛
|
|
||||||
// "Cannot create VirtualDisplay with non-current MediaProjection"。
|
|
||||||
if (starting || session != null) {
|
|
||||||
Log.w(TAG, "忽略重复启动请求(starting=$starting, running=${session != null})")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
starting = true
|
|
||||||
++generation
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/** 接收主控端投屏控制事件。 */
|
||||||
|
private fun handleMirrorAction(action: Int, message: String) {
|
||||||
|
Log.i(TAG, "投屏控制事件: ${MirrorAction.name(action)} $message")
|
||||||
|
when (action) {
|
||||||
|
MirrorAction.REQUEST -> {
|
||||||
|
if (state == State.STREAMING) {
|
||||||
|
// 已经在投屏,幂等回执即可。
|
||||||
|
session?.notifyMirror(MirrorAction.GRANTED)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 免确认模式下也要先有屏幕录制凭证,否则仍需要用户走一次授权。
|
||||||
|
if (!Prefs.mirrorConfirm(this) && projectionReady) {
|
||||||
|
beginMirroring()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
requestConfirmation()
|
||||||
|
}
|
||||||
|
|
||||||
|
MirrorAction.STOP -> endMirroring(reply = true)
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 弹窗 + 通知双通道确认:前台直接弹框,后台靠通知(有悬浮窗权限时也能直接弹框)。 */
|
||||||
|
private fun requestConfirmation() {
|
||||||
|
if (pendingRequest) {
|
||||||
|
Log.i(TAG, "已有待确认的投屏请求,忽略重复请求")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pendingRequest = true
|
||||||
|
showRequestNotification()
|
||||||
|
MirrorRequestActivity.launch(this)
|
||||||
|
handler.postDelayed(requestTimeout, REQUEST_TIMEOUT_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelPendingRequest() {
|
||||||
|
pendingRequest = false
|
||||||
|
handler.removeCallbacks(requestTimeout)
|
||||||
|
notificationManager?.cancel(REQUEST_NOTIFICATION_ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun denyPending(reason: String) {
|
||||||
|
if (!pendingRequest) return
|
||||||
|
cancelPendingRequest()
|
||||||
|
session?.notifyMirror(MirrorAction.DENIED, reason)
|
||||||
|
Log.i(TAG, "投屏请求被拒绝: $reason")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 校验权限并开始投屏(用户已确认)。 */
|
||||||
|
private fun beginMirroring() {
|
||||||
|
ensureSession()
|
||||||
|
// Android 14+ 要求 createVirtualDisplay 时存在 mediaProjection 类型的前台服务,
|
||||||
|
// 这里在真正开流前再确认一次(此时用户已授予屏幕录制权限)。
|
||||||
|
ensureForeground()
|
||||||
|
val current = session ?: return
|
||||||
|
val active = projection
|
||||||
|
if (active == null || !projectionReady) {
|
||||||
|
current.notifyMirror(MirrorAction.ERROR, "设备尚未授予屏幕录制权限")
|
||||||
|
Toast.makeText(this, "尚未授权屏幕录制,请先完成授权", Toast.LENGTH_SHORT).show()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cancelPendingRequest()
|
||||||
|
execWorker {
|
||||||
|
val started = current.beginMirroring(active)
|
||||||
|
handler.post {
|
||||||
|
if (started) {
|
||||||
|
state = State.STREAMING
|
||||||
|
current.notifyMirror(MirrorAction.GRANTED)
|
||||||
|
Log.i(TAG, "已开始投屏")
|
||||||
|
} else {
|
||||||
|
state = State.STANDBY
|
||||||
|
current.notifyMirror(MirrorAction.ERROR, "屏幕采集启动失败")
|
||||||
|
}
|
||||||
|
updateNotification()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun endMirroring(reply: Boolean) {
|
||||||
|
val current = session
|
||||||
|
if (current != null) execWorker { current.endMirroring() }
|
||||||
|
if (state == State.STREAMING) {
|
||||||
|
state = State.STANDBY
|
||||||
|
if (reply) session?.notifyMirror(MirrorAction.STOPPED)
|
||||||
|
updateNotification()
|
||||||
|
Log.i(TAG, "已停止投屏,回到待命")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拿到/复用 MediaProjection 凭证。真正创建 VirtualDisplay 在 beginMirroring 里。 */
|
||||||
|
private fun attachProjection(resultCode: Int, data: Intent, mirrorAfter: Boolean) {
|
||||||
|
ensureSession()
|
||||||
|
if (projection != null && projectionReady) {
|
||||||
|
if (mirrorAfter) beginMirroring()
|
||||||
|
return
|
||||||
|
}
|
||||||
val manager = getSystemService(MediaProjectionManager::class.java)
|
val manager = getSystemService(MediaProjectionManager::class.java)
|
||||||
val created = try {
|
val created = try {
|
||||||
manager?.getMediaProjection(resultCode, data)
|
manager?.getMediaProjection(resultCode, data)
|
||||||
} catch (e: Exception) {
|
} catch (error: Exception) {
|
||||||
Log.e(TAG, "getMediaProjection failed", e)
|
Log.e(TAG, "getMediaProjection 失败", error)
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
if (created == null) {
|
if (created == null) {
|
||||||
Toast.makeText(this, "MediaProjection 授权失败,请重新授权", Toast.LENGTH_SHORT).show()
|
Toast.makeText(this, "屏幕录制授权失败,请重试", Toast.LENGTH_SHORT).show()
|
||||||
stopProjectionSession()
|
session?.notifyMirror(MirrorAction.ERROR, "屏幕录制授权失败")
|
||||||
stopSelf()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
val callback = object : MediaProjection.Callback() {
|
val callback = object : MediaProjection.Callback() {
|
||||||
override fun onStop() {
|
override fun onStop() {
|
||||||
Log.i(TAG, "MediaProjection session stopped by system")
|
Log.i(TAG, "MediaProjection 已被系统或用户停止")
|
||||||
Handler(Looper.getMainLooper()).post {
|
handler.post {
|
||||||
// 只拆掉自己这一路,避免旧投影的回调把新会话拆了。
|
if (projection === created) {
|
||||||
if (isCurrentProjection(created)) {
|
releaseProjection()
|
||||||
stopProjectionSession()
|
session?.endMirroring()
|
||||||
stopSelf()
|
state = if (session != null) State.STANDBY else State.IDLE
|
||||||
|
updateNotification()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
projection = created
|
projection = created
|
||||||
projectionCallback = callback
|
projectionCallback = callback
|
||||||
created.registerCallback(callback, Handler(Looper.getMainLooper()))
|
projectionReady = true
|
||||||
|
created.registerCallback(callback, handler)
|
||||||
|
Log.i(TAG, "已获得屏幕录制凭证(尚未投屏)")
|
||||||
|
|
||||||
startBeacon()
|
if (mirrorAfter) beginMirroring()
|
||||||
val current = ReceiverSession(
|
|
||||||
context = this,
|
|
||||||
projection = created,
|
|
||||||
hostOverride = host,
|
|
||||||
signalingUrl = signalingUrl,
|
|
||||||
certificatePem = "",
|
|
||||||
)
|
|
||||||
session = current
|
|
||||||
|
|
||||||
// 连接建立包含 TCP 握手,必须在后台线程执行,避免服务主线程 ANR。
|
|
||||||
Thread {
|
|
||||||
try {
|
|
||||||
if (!isCurrentGeneration(gen)) {
|
|
||||||
current.stop()
|
|
||||||
return@Thread
|
|
||||||
}
|
|
||||||
current.start()
|
|
||||||
if (!isCurrentGeneration(gen)) {
|
|
||||||
current.stop()
|
|
||||||
return@Thread
|
|
||||||
}
|
|
||||||
isRunning = true
|
|
||||||
synchronized(stateLock) { if (gen == generation) starting = false }
|
|
||||||
Log.i(TAG, "Receiver session started")
|
|
||||||
} catch (e: Throwable) {
|
|
||||||
// 用 Throwable 兜底,避免异常逃逸后 starting 卡在 true 让会话再也无法重建。
|
|
||||||
Log.e(TAG, "Failed to start receiver session", e)
|
|
||||||
Handler(Looper.getMainLooper()).post { failStart(gen, e) }
|
|
||||||
}
|
|
||||||
}.start()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 启动失败:只有仍是当前世代时才拆会话,避免误杀新会话。 */
|
private fun releaseProjection() {
|
||||||
private fun failStart(gen: Int, error: Throwable) {
|
|
||||||
if (!isCurrentGeneration(gen)) return
|
|
||||||
val raw = error.message ?: error.javaClass.simpleName
|
|
||||||
val message = if (raw.contains("non-current", ignoreCase = true)) {
|
|
||||||
"投屏授权已失效,请重新点击「授权并开始投屏」"
|
|
||||||
} else {
|
|
||||||
raw
|
|
||||||
}
|
|
||||||
Toast.makeText(this, "连接失败: $message", Toast.LENGTH_SHORT).show()
|
|
||||||
stopProjectionSession()
|
|
||||||
stopSelf()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isCurrentGeneration(gen: Int): Boolean = synchronized(stateLock) { gen == generation }
|
|
||||||
|
|
||||||
private fun isCurrentProjection(target: MediaProjection): Boolean =
|
|
||||||
synchronized(stateLock) { projection === target }
|
|
||||||
|
|
||||||
/** 开启 UDP 信标:一边广播自身,一边收集主控端的 host 应答。 */
|
|
||||||
private fun startBeacon() {
|
|
||||||
if (beacon != null) return
|
|
||||||
val metrics = resources.displayMetrics
|
|
||||||
val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920)
|
|
||||||
val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080)
|
|
||||||
com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost()
|
|
||||||
beacon = com.ttstd.lancast.receiver.discovery.HostBeacon(
|
|
||||||
device = com.ttstd.lancast.receiver.discovery.HostBeacon.Offer(
|
|
||||||
id = java.util.UUID.randomUUID().toString(),
|
|
||||||
name = "Android Receiver",
|
|
||||||
model = Build.MODEL ?: "Android",
|
|
||||||
resolution = "${width}x$height",
|
|
||||||
),
|
|
||||||
).also { it.start() }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun stopProjectionSession() {
|
|
||||||
synchronized(stateLock) {
|
|
||||||
// 递增世代号,让仍在启动流程里的后台线程失效,不再碰已被顶掉的投影。
|
|
||||||
++generation
|
|
||||||
starting = false
|
|
||||||
}
|
|
||||||
session?.stop()
|
|
||||||
session = null
|
|
||||||
|
|
||||||
val callback = projectionCallback
|
val callback = projectionCallback
|
||||||
val current = projection
|
val current = projection
|
||||||
projectionCallback = null
|
projectionCallback = null
|
||||||
projection = null
|
projection = null
|
||||||
|
projectionReady = false
|
||||||
if (callback != null && current != null) {
|
if (callback != null && current != null) {
|
||||||
runCatching { current.unregisterCallback(callback) }
|
runCatching { current.unregisterCallback(callback) }
|
||||||
.onFailure { Log.w(TAG, "unregisterCallback failed", it) }
|
.onFailure { Log.w(TAG, "unregisterCallback 失败", it) }
|
||||||
}
|
}
|
||||||
// 必须显式 stop():否则系统仍把上一路投影视为「当前」投影,
|
|
||||||
// 下一次 createVirtualDisplay 会抛 non-current MediaProjection。
|
|
||||||
if (current != null) {
|
if (current != null) {
|
||||||
runCatching { current.stop() }
|
runCatching { current.stop() }
|
||||||
.onFailure { Log.w(TAG, "projection.stop() failed", it) }
|
.onFailure { Log.w(TAG, "projection.stop() 失败", it) }
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun teardown() {
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
pendingRequest = false
|
||||||
|
state = State.IDLE
|
||||||
|
isRunning = false
|
||||||
|
filePort = 0
|
||||||
|
session?.stop()
|
||||||
|
session = null
|
||||||
|
worker.shutdownNow()
|
||||||
|
fileServer?.stop()
|
||||||
|
fileServer = null
|
||||||
beacon?.stop()
|
beacon?.stop()
|
||||||
beacon = null
|
beacon = null
|
||||||
com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost()
|
HostBeacon.resetHost()
|
||||||
isRunning = false
|
releaseProjection()
|
||||||
|
notificationManager?.cancel(REQUEST_NOTIFICATION_ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
stopProjectionSession()
|
teardown()
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
} else {
|
} else {
|
||||||
@@ -282,32 +442,128 @@ class MediaProjectionService : Service() {
|
|||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? = null
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
private fun createNotificationChannel() {
|
// ------------------------------------------------------------------ 通知
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
||||||
val channel = NotificationChannel(
|
private fun ensureForeground() {
|
||||||
CHANNEL_ID,
|
val notification = buildServiceNotification()
|
||||||
"屏幕投屏服务",
|
try {
|
||||||
NotificationManager.IMPORTANCE_LOW
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
).apply {
|
startForeground(
|
||||||
description = "保持屏幕捕获服务在后台运行"
|
NOTIFICATION_ID,
|
||||||
|
notification,
|
||||||
|
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
startForeground(NOTIFICATION_ID, notification)
|
||||||
}
|
}
|
||||||
val manager = getSystemService(NotificationManager::class.java)
|
} catch (error: Exception) {
|
||||||
manager?.createNotificationChannel(channel)
|
Log.e(TAG, "startForeground(mediaProjection) 失败,降级为普通前台服务", error)
|
||||||
|
runCatching { startForeground(NOTIFICATION_ID, notification) }
|
||||||
|
.onFailure { Log.e(TAG, "startForeground 降级同样失败", it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun createNotification(): Notification {
|
private fun updateNotification() {
|
||||||
|
notificationManager?.notify(NOTIFICATION_ID, buildServiceNotification())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildServiceNotification(): Notification {
|
||||||
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
Notification.Builder(this, CHANNEL_ID)
|
Notification.Builder(this, CHANNEL_SERVICE)
|
||||||
} else {
|
} else {
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
Notification.Builder(this)
|
Notification.Builder(this)
|
||||||
}
|
}
|
||||||
|
val text = when (state) {
|
||||||
|
State.STREAMING -> "正在向主控端投屏"
|
||||||
|
State.STANDBY -> "待命中,等待主控端请求(未投屏)"
|
||||||
|
State.IDLE -> "服务启动中…"
|
||||||
|
}
|
||||||
|
val contentIntent = PendingIntent.getActivity(
|
||||||
|
this,
|
||||||
|
0,
|
||||||
|
Intent(this, MainActivity::class.java),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
return builder
|
return builder
|
||||||
.setContentTitle("Lancast 投屏服务")
|
.setContentTitle("TTSTD 远控服务")
|
||||||
.setContentText("屏幕投屏服务正在运行中")
|
.setContentText(text)
|
||||||
.setSmallIcon(android.R.drawable.ic_menu_camera)
|
.setSmallIcon(android.R.drawable.ic_menu_camera)
|
||||||
.setOngoing(true)
|
.setOngoing(true)
|
||||||
|
.setContentIntent(contentIntent)
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun showRequestNotification() {
|
||||||
|
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
Notification.Builder(this, CHANNEL_REQUEST)
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
Notification.Builder(this)
|
||||||
|
}
|
||||||
|
val allow = PendingIntent.getService(
|
||||||
|
this,
|
||||||
|
10,
|
||||||
|
Intent(this, MediaProjectionService::class.java).setAction(ACTION_MIRROR_START),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
val deny = PendingIntent.getService(
|
||||||
|
this,
|
||||||
|
11,
|
||||||
|
Intent(this, MediaProjectionService::class.java).setAction(ACTION_MIRROR_DENY),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
val open = PendingIntent.getActivity(
|
||||||
|
this,
|
||||||
|
12,
|
||||||
|
Intent(this, MirrorRequestActivity::class.java)
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
val notification = builder
|
||||||
|
.setContentTitle("投屏请求")
|
||||||
|
.setContentText("主控端请求查看您的屏幕,是否允许?")
|
||||||
|
.setSmallIcon(android.R.drawable.ic_menu_view)
|
||||||
|
.setPriority(Notification.PRIORITY_HIGH)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setContentIntent(open)
|
||||||
|
.addAction(Notification.Action.Builder(null, "允许", allow).build())
|
||||||
|
.addAction(Notification.Action.Builder(null, "拒绝", deny).build())
|
||||||
|
.build()
|
||||||
|
notificationManager?.notify(REQUEST_NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createNotificationChannels() {
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||||
|
val service = NotificationChannel(
|
||||||
|
CHANNEL_SERVICE,
|
||||||
|
"远控服务",
|
||||||
|
NotificationManager.IMPORTANCE_LOW,
|
||||||
|
).apply {
|
||||||
|
description = "保持待命/投屏服务在后台运行"
|
||||||
|
}
|
||||||
|
val request = NotificationChannel(
|
||||||
|
CHANNEL_REQUEST,
|
||||||
|
"投屏请求",
|
||||||
|
NotificationManager.IMPORTANCE_HIGH,
|
||||||
|
).apply {
|
||||||
|
description = "主控端请求投屏时提醒确认"
|
||||||
|
enableVibration(true)
|
||||||
|
}
|
||||||
|
notificationManager?.createNotificationChannel(service)
|
||||||
|
notificationManager?.createNotificationChannel(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun realMetrics(): DisplayMetrics {
|
||||||
|
val metrics = DisplayMetrics()
|
||||||
|
val manager = getSystemService(android.hardware.display.DisplayManager::class.java)
|
||||||
|
val display = manager?.getDisplay(Display.DEFAULT_DISPLAY)
|
||||||
|
if (display != null) {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
display.getRealMetrics(metrics)
|
||||||
|
} else {
|
||||||
|
metrics.setTo(resources.displayMetrics)
|
||||||
|
}
|
||||||
|
return metrics
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
package com.ttstd.lancast.receiver
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.media.projection.MediaProjectionManager
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.WindowManager
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 投屏确认页(透明主题,只显示一个对话框)。
|
||||||
|
*
|
||||||
|
* 主控端下发 [com.ttstd.lancast.receiver.protocol.MirrorAction.REQUEST] 后由 Service 拉起:
|
||||||
|
* - 用户拒绝 → 回 DENIED;
|
||||||
|
* - 用户允许且已有屏幕录制凭证 → 直接开流(GRANTED);
|
||||||
|
* - 用户允许但没有凭证 → 现场走系统授权,成功后带着凭证开流。
|
||||||
|
*/
|
||||||
|
class MirrorRequestActivity : Activity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "MirrorRequest"
|
||||||
|
private const val REQUEST_CAPTURE = 2001
|
||||||
|
private const val TIMEOUT_MS = 30_000L
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 尝试拉起确认页。Android 10+ 后台启动 Activity 会被系统拦截,
|
||||||
|
* 此时用户会看到服务发出的高优先级通知,点击同样能进入本页。
|
||||||
|
*/
|
||||||
|
fun launch(context: Context) {
|
||||||
|
try {
|
||||||
|
context.startActivity(
|
||||||
|
Intent(context, MirrorRequestActivity::class.java).apply {
|
||||||
|
addFlags(
|
||||||
|
Intent.FLAG_ACTIVITY_NEW_TASK or
|
||||||
|
Intent.FLAG_ACTIVITY_CLEAR_TOP or
|
||||||
|
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "无法直接拉起确认页: ${error.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
private var decided = false
|
||||||
|
private val timeout = Runnable { finishWith(false, "确认超时") }
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||||
|
handler.postDelayed(timeout, TIMEOUT_MS)
|
||||||
|
showDialog()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showDialog() {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle("投屏请求")
|
||||||
|
.setMessage("主控端请求查看您的屏幕。\n\n允许后开始投屏,您可随时在通知栏或本应用内停止。")
|
||||||
|
.setCancelable(false)
|
||||||
|
.setPositiveButton("允许") { _, _ -> onAllow() }
|
||||||
|
.setNegativeButton("拒绝") { _, _ -> finishWith(false, "用户拒绝") }
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onAllow() {
|
||||||
|
if (MediaProjectionService.hasProjection) {
|
||||||
|
MediaProjectionService.startMirroring(this)
|
||||||
|
finishWith(true, null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val manager = getSystemService(MediaProjectionManager::class.java)
|
||||||
|
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||||
|
super.onActivityResult(requestCode, resultCode, data)
|
||||||
|
if (requestCode != REQUEST_CAPTURE) return
|
||||||
|
if (resultCode == RESULT_OK && data != null) {
|
||||||
|
MediaProjectionService.attachProjection(this, resultCode, data, mirrorAfter = true)
|
||||||
|
finishWith(true, null)
|
||||||
|
} else {
|
||||||
|
finishWith(false, "用户取消授权")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun finishWith(granted: Boolean, reason: String?) {
|
||||||
|
if (decided) return
|
||||||
|
decided = true
|
||||||
|
handler.removeCallbacks(timeout)
|
||||||
|
if (!granted) MediaProjectionService.denyMirroring(this)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
if (!decided) {
|
||||||
|
// 页面被意外销毁(返回键等)也要给主控端一个明确答复,避免它一直等待。
|
||||||
|
decided = true
|
||||||
|
handler.removeCallbacks(timeout)
|
||||||
|
MediaProjectionService.denyMirroring(this)
|
||||||
|
}
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBackPressed() {
|
||||||
|
finishWith(false, "用户取消")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package com.ttstd.lancast.receiver
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import java.security.SecureRandom
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轻量配置存储。
|
||||||
|
*
|
||||||
|
* - [autoGrant]:主开关「允许远控」。打开后进入应用/开机自动启动待命服务,并自动发起一次
|
||||||
|
* 屏幕录制授权(仅获得凭证,不创建 VirtualDisplay,因此不会立即投屏)。
|
||||||
|
* - [fileServiceEnabled]:LocalSend 风格文件服务(浏览/下载/接收)。
|
||||||
|
* - [fileToken]:文件服务访问令牌,首次使用时生成,显示在主界面供主控端填写。
|
||||||
|
*/
|
||||||
|
object Prefs {
|
||||||
|
private const val NAME = "lancast_receiver_prefs"
|
||||||
|
private const val KEY_AUTO_GRANT = "auto_grant"
|
||||||
|
private const val KEY_FILE_SERVICE = "file_service_enabled"
|
||||||
|
private const val KEY_FILE_TOKEN = "file_token"
|
||||||
|
private const val KEY_MIRROR_CONFIRM = "mirror_confirm"
|
||||||
|
|
||||||
|
private fun prefs(context: Context) = context.applicationContext
|
||||||
|
.getSharedPreferences(NAME, Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
fun autoGrant(context: Context): Boolean = prefs(context).getBoolean(KEY_AUTO_GRANT, false)
|
||||||
|
|
||||||
|
fun setAutoGrant(context: Context, value: Boolean) {
|
||||||
|
prefs(context).edit().putBoolean(KEY_AUTO_GRANT, value).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 主控端请求投屏时是否需要本机弹窗确认(默认需要,安全优先)。 */
|
||||||
|
fun mirrorConfirm(context: Context): Boolean = prefs(context).getBoolean(KEY_MIRROR_CONFIRM, true)
|
||||||
|
|
||||||
|
fun setMirrorConfirm(context: Context, value: Boolean) {
|
||||||
|
prefs(context).edit().putBoolean(KEY_MIRROR_CONFIRM, value).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fileServiceEnabled(context: Context): Boolean =
|
||||||
|
prefs(context).getBoolean(KEY_FILE_SERVICE, true)
|
||||||
|
|
||||||
|
fun setFileServiceEnabled(context: Context, value: Boolean) {
|
||||||
|
prefs(context).edit().putBoolean(KEY_FILE_SERVICE, value).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fileToken(context: Context): String {
|
||||||
|
val store = prefs(context)
|
||||||
|
val existing = store.getString(KEY_FILE_TOKEN, null)
|
||||||
|
if (!existing.isNullOrEmpty()) return existing
|
||||||
|
return rotateFileToken(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun rotateFileToken(context: Context): String {
|
||||||
|
val random = SecureRandom()
|
||||||
|
val token = buildString {
|
||||||
|
repeat(8) { append('0' + random.nextInt(10)) }
|
||||||
|
}
|
||||||
|
prefs(context).edit().putString(KEY_FILE_TOKEN, token).apply()
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,15 @@
|
|||||||
package com.ttstd.lancast.receiver
|
package com.ttstd.lancast.receiver
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.hardware.display.DisplayManager
|
||||||
import android.media.projection.MediaProjection
|
import android.media.projection.MediaProjection
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
|
import android.util.DisplayMetrics
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.Display
|
||||||
import com.ttstd.lancast.receiver.capture.AudioCapturer
|
import com.ttstd.lancast.receiver.capture.AudioCapturer
|
||||||
import com.ttstd.lancast.receiver.capture.ScreenCapturer
|
import com.ttstd.lancast.receiver.capture.ScreenCapturer
|
||||||
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
|
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
|
||||||
@@ -13,6 +19,7 @@ import com.ttstd.lancast.receiver.discovery.NsdAdvertiser
|
|||||||
import com.ttstd.lancast.receiver.discovery.ReceiverAnnouncer
|
import com.ttstd.lancast.receiver.discovery.ReceiverAnnouncer
|
||||||
import com.ttstd.lancast.receiver.encode.OpusEncoder
|
import com.ttstd.lancast.receiver.encode.OpusEncoder
|
||||||
import com.ttstd.lancast.receiver.encode.VideoEncoder
|
import com.ttstd.lancast.receiver.encode.VideoEncoder
|
||||||
|
import com.ttstd.lancast.receiver.file.FileBrowser
|
||||||
import com.ttstd.lancast.receiver.file.FileService
|
import com.ttstd.lancast.receiver.file.FileService
|
||||||
import com.ttstd.lancast.receiver.input.InputInjector
|
import com.ttstd.lancast.receiver.input.InputInjector
|
||||||
import com.ttstd.lancast.receiver.protocol.ControlEvent
|
import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||||
@@ -21,9 +28,16 @@ import java.io.File
|
|||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 被控端会话。分两个阶段:
|
||||||
|
*
|
||||||
|
* 1. **待命**([start]):只做设备广播 + 控制通道拨号,不占用编码器、不创建 VirtualDisplay,
|
||||||
|
* 因此不会投屏,主控端可以随时下发投屏请求。
|
||||||
|
* 2. **投屏**([beginMirroring]):拿到 MediaProjection 后按本机真实屏幕尺寸建立
|
||||||
|
* 编码器 + VirtualDisplay + 音频采集,期间跟随屏幕旋转/分辨率变化自动重建。
|
||||||
|
*/
|
||||||
class ReceiverSession(
|
class ReceiverSession(
|
||||||
private val context: Context,
|
private val context: Context,
|
||||||
private val projection: MediaProjection,
|
|
||||||
/** 主控端地址;为空时通过 UDP 信标自动发现(推荐)。 */
|
/** 主控端地址;为空时通过 UDP 信标自动发现(推荐)。 */
|
||||||
private val hostOverride: String,
|
private val hostOverride: String,
|
||||||
private val signalingUrl: String,
|
private val signalingUrl: String,
|
||||||
@@ -31,16 +45,33 @@ class ReceiverSession(
|
|||||||
private val preferH265: Boolean = false,
|
private val preferH265: Boolean = false,
|
||||||
private val bitrateMbps: Int = 8,
|
private val bitrateMbps: Int = 8,
|
||||||
) {
|
) {
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "ReceiverSession"
|
||||||
|
|
||||||
|
/** 编码长边上限,兼顾清晰度与局域网带宽。 */
|
||||||
|
private const val MAX_LONG_SIDE = 1920
|
||||||
|
}
|
||||||
|
|
||||||
private val executor = Executors.newFixedThreadPool(3)
|
private val executor = Executors.newFixedThreadPool(3)
|
||||||
private val clipboard = ClipboardBridge(context)
|
private val clipboard = ClipboardBridge(context)
|
||||||
private val injector = InputInjector(context)
|
private val injector = InputInjector(context)
|
||||||
private val fileService = FileService(File(context.filesDir, "file-inbox"))
|
private val fileService = FileService(File(context.filesDir, "file-inbox"), FileBrowser(context))
|
||||||
private val opusEncoder = OpusEncoder()
|
private val opusEncoder = OpusEncoder()
|
||||||
|
private val displayManager = context.getSystemService(DisplayManager::class.java)
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
private val fingerprint: String = ""
|
private val fingerprint: String = ""
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var transport: ReceiverTransport? = null
|
private var transport: ReceiverTransport? = null
|
||||||
|
|
||||||
|
/** 主控端投屏请求回调:(action, message),由 Service 绑定。 */
|
||||||
|
@Volatile
|
||||||
|
var onMirrorRequest: ((Int, String) -> Unit)? = null
|
||||||
|
|
||||||
|
/** 投屏过程中采集链路重建失败的回调。 */
|
||||||
|
@Volatile
|
||||||
|
var onStreamingLost: (() -> Unit)? = null
|
||||||
|
|
||||||
private val encoder = VideoEncoder { buffer, info ->
|
private val encoder = VideoEncoder { buffer, info ->
|
||||||
transport?.sendVideo(buffer, info, preferH265)
|
transport?.sendVideo(buffer, info, preferH265)
|
||||||
}
|
}
|
||||||
@@ -49,38 +80,150 @@ class ReceiverSession(
|
|||||||
private var audio: AudioCapturer? = null
|
private var audio: AudioCapturer? = null
|
||||||
private var announcer: ReceiverAnnouncer? = null
|
private var announcer: ReceiverAnnouncer? = null
|
||||||
private var nsdAdvertiser: NsdAdvertiser? = null
|
private var nsdAdvertiser: NsdAdvertiser? = null
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var running = false
|
private var running = false
|
||||||
|
|
||||||
fun start() {
|
/** 是否正在投屏(采集链路已建立)。 */
|
||||||
if (running) return
|
@Volatile
|
||||||
running = true
|
var mirroring = false
|
||||||
val metrics = context.resources.displayMetrics
|
private set
|
||||||
val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920)
|
|
||||||
val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080)
|
|
||||||
|
|
||||||
try {
|
private val captureLock = Any()
|
||||||
startCapture(width, height, metrics.densityDpi)
|
private var projection: MediaProjection? = null
|
||||||
startPublishing(width, height)
|
private var captureWidth = 0
|
||||||
} catch (e: Exception) {
|
private var captureHeight = 0
|
||||||
// 启动失败必须彻底释放已申请的编码器/虚拟显示,否则会残留并阻塞下次启动。
|
private var captureDensity = 0
|
||||||
running = false
|
|
||||||
stop()
|
private val displayListener = object : DisplayManager.DisplayListener {
|
||||||
throw e
|
override fun onDisplayAdded(displayId: Int) = Unit
|
||||||
|
|
||||||
|
override fun onDisplayRemoved(displayId: Int) = Unit
|
||||||
|
|
||||||
|
override fun onDisplayChanged(displayId: Int) {
|
||||||
|
if (displayId == Display.DEFAULT_DISPLAY) scheduleResize()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 建立采集链路:编码器 + VirtualDisplay + 剪贴板。 */
|
/** 待命启动:只建立发现与控制链路。 */
|
||||||
private fun startCapture(width: Int, height: Int, densityDpi: Int) {
|
fun start() {
|
||||||
encoder.start(width, height, 30, bitrateMbps * 1_000_000, preferH265)
|
if (running) return
|
||||||
val surface = encoder.inputSurface
|
running = true
|
||||||
?: throw IllegalStateException("视频编码器未返回输入 Surface")
|
displayManager?.registerDisplayListener(displayListener, mainHandler)
|
||||||
capturer = ScreenCapturer(projection, surface, densityDpi).also { it.start(width, height) }
|
opusEncoder.start()
|
||||||
clipboard.start { text -> transport?.sendControl(ControlEvent.Clipboard(text)) }
|
clipboard.start { text -> transport?.sendControl(ControlEvent.Clipboard(text)) }
|
||||||
|
startPublishing()
|
||||||
|
executor.execute {
|
||||||
|
while (running) {
|
||||||
|
// 与采集链路的建立/重建互斥,避免旋转重建时两个线程同时操作 MediaCodec。
|
||||||
|
synchronized(captureLock) { encoder.drain() }
|
||||||
|
try {
|
||||||
|
Thread.sleep(if (mirroring) 4 else 20)
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
return@execute
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
executor.execute { connectWhenHostReady() }
|
||||||
|
Log.i(TAG, "会话进入待命状态(未投屏)")
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 发布设备信息 / 音频采集 / 拨号线程。 */
|
/**
|
||||||
private fun startPublishing(width: Int, height: Int) {
|
* 开始投屏。必须在 [start] 之后、且持有有效的 MediaProjection 时调用。
|
||||||
|
* @return 是否成功建立采集链路。
|
||||||
|
*/
|
||||||
|
fun beginMirroring(projection: MediaProjection): Boolean {
|
||||||
|
if (!running) return false
|
||||||
|
synchronized(captureLock) {
|
||||||
|
if (mirroring) return true
|
||||||
|
this.projection = projection
|
||||||
|
return try {
|
||||||
|
startCapture()
|
||||||
|
mirroring = true
|
||||||
|
Log.i(TAG, "开始投屏 ${captureWidth}x$captureHeight")
|
||||||
|
true
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.e(TAG, "开启采集失败", error)
|
||||||
|
releaseCapture()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 停止投屏但保留会话(回到待命)。 */
|
||||||
|
fun endMirroring() {
|
||||||
|
synchronized(captureLock) {
|
||||||
|
if (!mirroring) return
|
||||||
|
mirroring = false
|
||||||
|
releaseCapture()
|
||||||
|
Log.i(TAG, "已停止投屏,回到待命状态")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 回送投屏应答给主控端。 */
|
||||||
|
fun notifyMirror(action: Int, message: String = "") {
|
||||||
|
transport?.sendMirror(action, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
val connected: Boolean get() = transport?.keyEstablished == true
|
||||||
|
|
||||||
|
private fun startCapture() {
|
||||||
|
val current = projection ?: throw IllegalStateException("未持有屏幕录制授权")
|
||||||
|
val size = currentScreenSize()
|
||||||
|
captureWidth = size[0]
|
||||||
|
captureHeight = size[1]
|
||||||
|
captureDensity = currentDensity()
|
||||||
|
|
||||||
|
encoder.start(captureWidth, captureHeight, 30, bitrateMbps * 1_000_000, preferH265)
|
||||||
|
val surface = encoder.inputSurface
|
||||||
|
?: throw IllegalStateException("视频编码器未返回输入 Surface")
|
||||||
|
capturer = ScreenCapturer(current, surface, captureDensity).also {
|
||||||
|
it.start(captureWidth, captureHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
audio = AudioCapturer(current) { pcm ->
|
||||||
|
val active = transport ?: return@AudioCapturer
|
||||||
|
opusEncoder.encode(pcm).forEach { packet ->
|
||||||
|
active.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
|
||||||
|
}
|
||||||
|
}.also { it.start() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun releaseCapture() {
|
||||||
|
runCatching { capturer?.stop() }.onFailure { Log.w(TAG, "释放采集失败", it) }
|
||||||
|
capturer = null
|
||||||
|
runCatching { audio?.stop() }.onFailure { Log.w(TAG, "释放音频采集失败", it) }
|
||||||
|
audio = null
|
||||||
|
runCatching { encoder.stop() }.onFailure { Log.w(TAG, "释放编码器失败", it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 屏幕旋转或分辨率变化后,按新尺寸重建编码器与 VirtualDisplay。 */
|
||||||
|
private fun scheduleResize() {
|
||||||
|
if (!mirroring) return
|
||||||
|
executor.execute {
|
||||||
|
synchronized(captureLock) {
|
||||||
|
if (!mirroring) return@execute
|
||||||
|
val size = currentScreenSize()
|
||||||
|
if (size[0] == captureWidth && size[1] == captureHeight) return@execute
|
||||||
|
Log.i(TAG, "屏幕尺寸变化 ${captureWidth}x$captureHeight -> ${size[0]}x${size[1]},重建采集")
|
||||||
|
releaseCapture()
|
||||||
|
try {
|
||||||
|
startCapture()
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.e(TAG, "按新尺寸重建采集失败", error)
|
||||||
|
mirroring = false
|
||||||
|
releaseCapture()
|
||||||
|
onStreamingLost?.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 发布设备信息并启动控制通道拨号。 */
|
||||||
|
private fun startPublishing() {
|
||||||
|
val size = currentScreenSize()
|
||||||
val device = AnnouncedDevice(
|
val device = AnnouncedDevice(
|
||||||
id = UUID.randomUUID().toString(),
|
id = UUID.randomUUID().toString(),
|
||||||
name = "Android Receiver",
|
name = "Android Receiver",
|
||||||
@@ -88,33 +231,17 @@ class ReceiverSession(
|
|||||||
mediaPort = 41000,
|
mediaPort = 41000,
|
||||||
controlPort = 41001,
|
controlPort = 41001,
|
||||||
fingerprint = this@ReceiverSession.fingerprint,
|
fingerprint = this@ReceiverSession.fingerprint,
|
||||||
capabilities = listOf("h264", "opus", "uibc", "clipboard", "file"),
|
capabilities = listOf(
|
||||||
|
"h264", "opus", "uibc", "clipboard", "file", "mirror-request", "file-browse",
|
||||||
|
),
|
||||||
model = Build.MODEL,
|
model = Build.MODEL,
|
||||||
resolution = "${width}x$height",
|
resolution = "${size[0]}x${size[1]}",
|
||||||
)
|
)
|
||||||
// 信令服务器是跨网段兜底:没有配置(空串)时不必启动,避免无谓的失败请求。
|
// 信令服务器是跨网段兜底:没有配置(空串)时不必启动,避免无谓的失败请求。
|
||||||
if (signalingUrl.isNotBlank()) {
|
if (signalingUrl.isNotBlank()) {
|
||||||
announcer = ReceiverAnnouncer(signalingUrl, device).also { it.start() }
|
announcer = ReceiverAnnouncer(signalingUrl, device).also { it.start() }
|
||||||
}
|
}
|
||||||
nsdAdvertiser = NsdAdvertiser(context, device).also { it.start() }
|
nsdAdvertiser = NsdAdvertiser(context, device).also { it.start() }
|
||||||
|
|
||||||
opusEncoder.start()
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
|
||||||
audio = AudioCapturer(projection) { pcm ->
|
|
||||||
val current = transport ?: return@AudioCapturer
|
|
||||||
opusEncoder.encode(pcm).forEach { packet ->
|
|
||||||
current.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
|
|
||||||
}
|
|
||||||
}.also { it.start() }
|
|
||||||
}
|
|
||||||
|
|
||||||
executor.execute {
|
|
||||||
while (running) {
|
|
||||||
encoder.drain()
|
|
||||||
Thread.sleep(4)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
executor.execute { connectWhenHostReady() }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 等主控端地址可用(信标发现或手动覆盖)后再拨号,之后由 transport 自己重连。 */
|
/** 等主控端地址可用(信标发现或手动覆盖)后再拨号,之后由 transport 自己重连。 */
|
||||||
@@ -133,6 +260,7 @@ class ReceiverSession(
|
|||||||
clipboard,
|
clipboard,
|
||||||
fileService,
|
fileService,
|
||||||
)
|
)
|
||||||
|
created.onMirrorEvent = { action, message -> onMirrorRequest?.invoke(action, message) }
|
||||||
transport = created
|
transport = created
|
||||||
created.start()
|
created.start()
|
||||||
return
|
return
|
||||||
@@ -147,18 +275,53 @@ class ReceiverSession(
|
|||||||
|
|
||||||
fun stop() {
|
fun stop() {
|
||||||
running = false
|
running = false
|
||||||
capturer?.stop()
|
displayManager?.unregisterDisplayListener(displayListener)
|
||||||
audio?.stop()
|
endMirroring()
|
||||||
clipboard.stop()
|
clipboard.stop()
|
||||||
announcer?.stop()
|
announcer?.stop()
|
||||||
nsdAdvertiser?.stop()
|
nsdAdvertiser?.stop()
|
||||||
opusEncoder.stop()
|
opusEncoder.stop()
|
||||||
transport?.stop()
|
transport?.stop()
|
||||||
transport = null
|
transport = null
|
||||||
encoder.stop()
|
runCatching { encoder.stop() }
|
||||||
executor.shutdownNow()
|
executor.shutdownNow()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 本机真实屏幕尺寸(跟随旋转),长边限制在 [MAX_LONG_SIDE] 内,宽高取偶数。 */
|
||||||
|
private fun currentScreenSize(): IntArray {
|
||||||
|
val metrics = DisplayMetrics()
|
||||||
|
val display = displayManager?.getDisplay(Display.DEFAULT_DISPLAY)
|
||||||
|
if (display != null) {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
display.getRealMetrics(metrics)
|
||||||
|
} else {
|
||||||
|
metrics.setTo(context.resources.displayMetrics)
|
||||||
|
}
|
||||||
|
return fit(metrics.widthPixels, metrics.heightPixels)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun currentDensity(): Int {
|
||||||
|
val display = displayManager?.getDisplay(Display.DEFAULT_DISPLAY)
|
||||||
|
?: return context.resources.displayMetrics.densityDpi
|
||||||
|
val metrics = DisplayMetrics()
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
display.getRealMetrics(metrics)
|
||||||
|
return if (metrics.densityDpi > 0) metrics.densityDpi else context.resources.displayMetrics.densityDpi
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fit(width: Int, height: Int): IntArray {
|
||||||
|
var w = width.coerceAtLeast(16)
|
||||||
|
var h = height.coerceAtLeast(16)
|
||||||
|
val longSide = maxOf(w, h)
|
||||||
|
if (longSide > MAX_LONG_SIDE) {
|
||||||
|
val scale = MAX_LONG_SIDE.toDouble() / longSide
|
||||||
|
w = (w * scale).toInt()
|
||||||
|
h = (h * scale).toInt()
|
||||||
|
}
|
||||||
|
// H.264/HEVC 要求偶数尺寸。
|
||||||
|
return intArrayOf(w.coerceAtLeast(16) and 1.inv(), h.coerceAtLeast(16) and 1.inv())
|
||||||
|
}
|
||||||
|
|
||||||
private val localIp: String
|
private val localIp: String
|
||||||
get() = java.net.NetworkInterface.getNetworkInterfaces().toList()
|
get() = java.net.NetworkInterface.getNetworkInterfaces().toList()
|
||||||
.flatMap { it.inetAddresses.toList() }
|
.flatMap { it.inetAddresses.toList() }
|
||||||
|
|||||||
+8
-1
@@ -160,7 +160,14 @@ class HostBeacon(
|
|||||||
put("media", mediaPort)
|
put("media", mediaPort)
|
||||||
put("audio", audioPort)
|
put("audio", audioPort)
|
||||||
put("fp", "")
|
put("fp", "")
|
||||||
put("cap", JSONArray(listOf("h264", "opus", "uibc", "clipboard", "file")))
|
put(
|
||||||
|
"cap",
|
||||||
|
JSONArray(
|
||||||
|
listOf(
|
||||||
|
"h264", "opus", "uibc", "clipboard", "file", "mirror-request", "file-browse",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
return json.toString().toByteArray(Charsets.UTF_8)
|
return json.toString().toByteArray(Charsets.UTF_8)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package com.ttstd.lancast.receiver.file
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 只读目录浏览 + 路径越权校验。
|
||||||
|
*
|
||||||
|
* 所有对外暴露的路径都必须是 [allowedRoots] 之下的规范路径,避免 `../` 穿越读到私有数据。
|
||||||
|
*/
|
||||||
|
class FileBrowser(private val context: Context) {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** 单次列举的最大条目数,防止一次请求拉爆内存/带宽。 */
|
||||||
|
private const val MAX_ENTRIES = 2000
|
||||||
|
}
|
||||||
|
|
||||||
|
fun allowedRoots(): List<File> = StorageAccess.roots(context)
|
||||||
|
|
||||||
|
fun rootsJson(): JSONArray {
|
||||||
|
val array = JSONArray()
|
||||||
|
allowedRoots().forEach { root ->
|
||||||
|
array.put(
|
||||||
|
JSONObject()
|
||||||
|
.put("name", root.name.ifEmpty { root.absolutePath })
|
||||||
|
.put("path", root.absolutePath),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return array
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把请求路径规范化,并校验仍落在允许的根目录内。 */
|
||||||
|
fun resolve(path: String): File {
|
||||||
|
val roots = allowedRoots()
|
||||||
|
if (roots.isEmpty()) throw SecurityException("没有可访问的存储目录")
|
||||||
|
val candidate = if (path.isBlank()) roots.first() else File(path)
|
||||||
|
val canonical = try {
|
||||||
|
candidate.canonicalFile
|
||||||
|
} catch (error: Exception) {
|
||||||
|
throw SecurityException("非法路径: $path")
|
||||||
|
}
|
||||||
|
val allowed = roots.any { root ->
|
||||||
|
val rootPath = try {
|
||||||
|
root.canonicalPath
|
||||||
|
} catch (_: Exception) {
|
||||||
|
root.absolutePath
|
||||||
|
}
|
||||||
|
canonical.path == rootPath || canonical.path.startsWith(rootPath + File.separator)
|
||||||
|
}
|
||||||
|
if (!allowed) throw SecurityException("路径不在允许范围内: $path")
|
||||||
|
return canonical
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 列举目录,返回 `{path, parent, roots, entries:[{name,path,dir,size,mtime}]}`。 */
|
||||||
|
fun list(path: String): JSONObject {
|
||||||
|
val dir = resolve(path)
|
||||||
|
if (!dir.exists()) throw IllegalArgumentException("目录不存在: ${dir.absolutePath}")
|
||||||
|
if (!dir.isDirectory) throw IllegalArgumentException("不是目录: ${dir.absolutePath}")
|
||||||
|
|
||||||
|
val entryArray = JSONArray()
|
||||||
|
val children = dir.listFiles() ?: emptyArray()
|
||||||
|
children.asSequence()
|
||||||
|
.filterNot { it.name.startsWith(".") }
|
||||||
|
.sortedWith(compareByDescending<File> { it.isDirectory }.thenBy { it.name.lowercase() })
|
||||||
|
.take(MAX_ENTRIES)
|
||||||
|
.forEach { child ->
|
||||||
|
entryArray.put(
|
||||||
|
JSONObject()
|
||||||
|
.put("name", child.name)
|
||||||
|
.put("path", child.absolutePath)
|
||||||
|
.put("dir", child.isDirectory)
|
||||||
|
.put("size", if (child.isDirectory) 0L else child.length())
|
||||||
|
.put("mtime", child.lastModified()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val parent = dir.parentFile
|
||||||
|
val parentPath = if (parent != null) {
|
||||||
|
try {
|
||||||
|
resolve(parent.absolutePath).absolutePath
|
||||||
|
} catch (_: SecurityException) {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
|
||||||
|
return JSONObject()
|
||||||
|
.put("path", dir.absolutePath)
|
||||||
|
.put("parent", parentPath)
|
||||||
|
.put("roots", rootsJson())
|
||||||
|
.put("entries", entryArray)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 计算上传落盘目标文件(限定在允许范围内,文件名做基本清洗)。 */
|
||||||
|
fun uploadTarget(dirPath: String, name: String): File {
|
||||||
|
val dir = resolve(dirPath)
|
||||||
|
if (!dir.isDirectory) throw IllegalArgumentException("目标不是目录")
|
||||||
|
val safe = name.replace('/', '_').replace('\\', '_').replace("..", "_").ifEmpty {
|
||||||
|
"upload-${System.currentTimeMillis()}"
|
||||||
|
}
|
||||||
|
return File(dir, safe)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
package com.ttstd.lancast.receiver.file
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Build
|
||||||
|
import android.util.Log
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.BufferedInputStream
|
||||||
|
import java.io.BufferedOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileInputStream
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.io.OutputStream
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.ServerSocket
|
||||||
|
import java.net.Socket
|
||||||
|
import java.net.URLDecoder
|
||||||
|
import java.nio.charset.StandardCharsets
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LocalSend 风格的文件服务(默认 53317,被占用时顺延)。
|
||||||
|
*
|
||||||
|
* 提供的能力:
|
||||||
|
* - `GET /api/localsend/v1/info`、`/api/localsend/v2/info`:LocalSend 设备信息(无需令牌)
|
||||||
|
* - `POST /api/localsend/v1/register`、`/v2/register`:LocalSend 注册握手(无需令牌)
|
||||||
|
* - `GET /browse?path=`:浏览 Android 目录(返回 JSON)
|
||||||
|
* - `GET /download?path=`:下载单个文件
|
||||||
|
* - `POST /api/localsend/v2/upload?path=&name=`:接收文件到指定目录
|
||||||
|
* - `POST /mirror/request`:触发一次投屏确认(便于不开主控端也能验证)
|
||||||
|
*
|
||||||
|
* 除 info/register 外都要求 `?token=`(或 `X-Lancast-Token` 头)与主界面显示的一致。
|
||||||
|
*/
|
||||||
|
class FileHttpServer(
|
||||||
|
private val context: Context,
|
||||||
|
private val tokenProvider: () -> String,
|
||||||
|
private val onMirrorRequest: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "FileHttpServer"
|
||||||
|
private val CANDIDATE_PORTS = intArrayOf(53317, 53318, 53319, 53320)
|
||||||
|
private const val MAX_BODY = 64L * 1024 * 1024
|
||||||
|
}
|
||||||
|
|
||||||
|
private val browser = FileBrowser(context)
|
||||||
|
private val workers = Executors.newCachedThreadPool()
|
||||||
|
private var serverSocket: ServerSocket? = null
|
||||||
|
private var acceptThread: Thread? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var running = false
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var boundPort: Int = 0
|
||||||
|
private set
|
||||||
|
|
||||||
|
val isRunning: Boolean get() = running
|
||||||
|
|
||||||
|
fun start(): Int {
|
||||||
|
if (running) return boundPort
|
||||||
|
for (port in CANDIDATE_PORTS) {
|
||||||
|
try {
|
||||||
|
val socket = ServerSocket().apply {
|
||||||
|
reuseAddress = true
|
||||||
|
bind(InetSocketAddress(port))
|
||||||
|
}
|
||||||
|
serverSocket = socket
|
||||||
|
boundPort = port
|
||||||
|
running = true
|
||||||
|
acceptThread = Thread({ acceptLoop(socket) }, "lancast-file-http").apply {
|
||||||
|
isDaemon = true
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
Log.i(TAG, "文件服务已启动,端口 $port")
|
||||||
|
return port
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "端口 $port 不可用: ${error.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log.e(TAG, "没有可用端口,文件服务未启动")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
running = false
|
||||||
|
try {
|
||||||
|
serverSocket?.close()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
serverSocket = null
|
||||||
|
acceptThread?.interrupt()
|
||||||
|
acceptThread = null
|
||||||
|
workers.shutdownNow()
|
||||||
|
boundPort = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun acceptLoop(socket: ServerSocket) {
|
||||||
|
while (running) {
|
||||||
|
val client = try {
|
||||||
|
socket.accept()
|
||||||
|
} catch (error: Exception) {
|
||||||
|
if (!running) return
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
workers.execute { handle(client) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handle(socket: Socket) {
|
||||||
|
socket.use { client ->
|
||||||
|
client.soTimeout = 15000
|
||||||
|
val input = BufferedInputStream(client.getInputStream())
|
||||||
|
val output = BufferedOutputStream(client.getOutputStream())
|
||||||
|
try {
|
||||||
|
val requestLine = readLine(input) ?: return
|
||||||
|
val parts = requestLine.split(' ')
|
||||||
|
if (parts.size < 2) return
|
||||||
|
val method = parts[0].uppercase()
|
||||||
|
val target = parts[1]
|
||||||
|
|
||||||
|
val headers = mutableMapOf<String, String>()
|
||||||
|
while (true) {
|
||||||
|
val line = readLine(input) ?: break
|
||||||
|
if (line.isEmpty()) break
|
||||||
|
val index = line.indexOf(':')
|
||||||
|
if (index > 0) {
|
||||||
|
headers[line.substring(0, index).trim().lowercase()] = line.substring(index + 1).trim()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val body = readBody(input, headers)
|
||||||
|
val path = target.substringBefore('?')
|
||||||
|
val query = parseQuery(target.substringAfter('?', ""))
|
||||||
|
|
||||||
|
val response = try {
|
||||||
|
route(method, path, query, headers, body)
|
||||||
|
} catch (error: SecurityException) {
|
||||||
|
jsonResponse(403, error.message ?: "禁止访问")
|
||||||
|
} catch (error: Exception) {
|
||||||
|
jsonResponse(400, error.message ?: "请求失败")
|
||||||
|
}
|
||||||
|
writeResponse(output, response)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Log.w(TAG, "连接处理失败: ${error.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun route(
|
||||||
|
method: String,
|
||||||
|
path: String,
|
||||||
|
query: Map<String, String>,
|
||||||
|
headers: Map<String, String>,
|
||||||
|
body: ByteArray,
|
||||||
|
): Response {
|
||||||
|
// LocalSend 发现/注册接口不需要令牌,方便桌面端识别设备。
|
||||||
|
if (path == "/api/localsend/v1/info" || path == "/api/localsend/v2/info") {
|
||||||
|
return jsonResponse(200, infoJson())
|
||||||
|
}
|
||||||
|
if (path.endsWith("/register")) {
|
||||||
|
return Response(204, "application/json")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!authorized(query, headers)) {
|
||||||
|
return jsonResponse(403, "令牌无效,请填写主界面显示的文件服务令牌")
|
||||||
|
}
|
||||||
|
|
||||||
|
return when (path) {
|
||||||
|
"/", "/index.html" -> htmlResponse(indexHtml())
|
||||||
|
"/browse" -> jsonResponse(200, browser.list(query["path"] ?: "").toString())
|
||||||
|
"/download" -> download(query["path"] ?: "")
|
||||||
|
"/api/localsend/v2/upload", "/api/localsend/v1/upload" -> upload(query, body)
|
||||||
|
"/mirror/request" -> {
|
||||||
|
onMirrorRequest(query["host"] ?: "")
|
||||||
|
jsonResponse(200, JSONObject().put("ok", true).toString())
|
||||||
|
}
|
||||||
|
else -> jsonResponse(404, "未知接口: $path")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun download(path: String): Response {
|
||||||
|
if (path.isBlank()) return jsonResponse(400, "缺少 path 参数")
|
||||||
|
val file = browser.resolve(path)
|
||||||
|
if (!file.exists() || !file.isFile) return jsonResponse(404, "文件不存在")
|
||||||
|
val mime = mimeOf(file.name)
|
||||||
|
return Response(
|
||||||
|
code = 200,
|
||||||
|
contentType = mime,
|
||||||
|
file = file,
|
||||||
|
headers = listOf("Content-Disposition" to "attachment; filename=\"${file.name}\""),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun upload(query: Map<String, String>, body: ByteArray): Response {
|
||||||
|
val dir = query["path"] ?: browser.allowedRoots().firstOrNull()?.absolutePath
|
||||||
|
?: return jsonResponse(400, "缺少 path 参数")
|
||||||
|
val name = query["name"] ?: "upload-${System.currentTimeMillis()}"
|
||||||
|
val target = browser.uploadTarget(dir, name)
|
||||||
|
target.parentFile?.mkdirs()
|
||||||
|
target.outputStream().use { it.write(body) }
|
||||||
|
return jsonResponse(
|
||||||
|
200,
|
||||||
|
JSONObject()
|
||||||
|
.put("ok", true)
|
||||||
|
.put("path", target.absolutePath)
|
||||||
|
.put("size", target.length())
|
||||||
|
.toString(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun authorized(query: Map<String, String>, headers: Map<String, String>): Boolean {
|
||||||
|
val expected = tokenProvider()
|
||||||
|
if (expected.isEmpty()) return true
|
||||||
|
val provided = query["token"] ?: headers["x-lancast-token"]
|
||||||
|
return provided == expected
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun infoJson(): String = JSONObject().apply {
|
||||||
|
put("alias", "TTSTD Receiver")
|
||||||
|
put("version", "2.1")
|
||||||
|
put("deviceModel", Build.MODEL ?: "Android")
|
||||||
|
put("deviceType", "mobile")
|
||||||
|
put("fingerprint", tokenProvider())
|
||||||
|
put("port", boundPort)
|
||||||
|
put("protocol", "http")
|
||||||
|
put("download", false)
|
||||||
|
put("announce", false)
|
||||||
|
}.toString()
|
||||||
|
|
||||||
|
private fun indexHtml(): String = """
|
||||||
|
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>TTSTD 文件服务</title>
|
||||||
|
<style>
|
||||||
|
body{font-family:system-ui,sans-serif;margin:0;padding:24px;background:#111;color:#eee}
|
||||||
|
h1{font-size:18px;margin:0 0 12px}
|
||||||
|
code{background:#222;padding:2px 6px;border-radius:4px}
|
||||||
|
a{color:#4da3ff;text-decoration:none}
|
||||||
|
ul{padding-left:18px;line-height:1.9}
|
||||||
|
</style></head><body>
|
||||||
|
<h1>TTSTD 文件服务</h1>
|
||||||
|
<p>本页仅用于自检,实际请由主控端访问接口。</p>
|
||||||
|
<ul>
|
||||||
|
<li><a href="/api/localsend/v2/info">/api/localsend/v2/info</a></li>
|
||||||
|
<li><a href="/browse?token=__TOKEN__">/browse</a> 浏览根目录</li>
|
||||||
|
<li><code>GET /download?path=&token=</code> 下载文件</li>
|
||||||
|
<li><code>POST /api/localsend/v2/upload?path=&name=&token=</code> 接收文件</li>
|
||||||
|
<li><code>POST /mirror/request?token=</code> 触发投屏确认</li>
|
||||||
|
</ul></body></html>
|
||||||
|
""".trimIndent().replace("__TOKEN__", tokenProvider())
|
||||||
|
|
||||||
|
private fun mimeOf(name: String): String {
|
||||||
|
val extension = name.substringAfterLast('.', "").lowercase()
|
||||||
|
return when (extension) {
|
||||||
|
"txt", "log", "md" -> "text/plain; charset=utf-8"
|
||||||
|
"json" -> "application/json; charset=utf-8"
|
||||||
|
"html", "htm" -> "text/html; charset=utf-8"
|
||||||
|
"jpg", "jpeg" -> "image/jpeg"
|
||||||
|
"png" -> "image/png"
|
||||||
|
"gif" -> "image/gif"
|
||||||
|
"webp" -> "image/webp"
|
||||||
|
"mp4" -> "video/mp4"
|
||||||
|
"mkv" -> "video/x-matroska"
|
||||||
|
"mp3" -> "audio/mpeg"
|
||||||
|
"apk" -> "application/vnd.android.package-archive"
|
||||||
|
"pdf" -> "application/pdf"
|
||||||
|
"zip" -> "application/zip"
|
||||||
|
else -> "application/octet-stream"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun jsonResponse(code: Int, message: String): Response {
|
||||||
|
val payload = if (message.trimStart().startsWith("{")) {
|
||||||
|
message
|
||||||
|
} else {
|
||||||
|
JSONObject().put("error", message).toString()
|
||||||
|
}
|
||||||
|
return Response(code, "application/json; charset=utf-8", payload.toByteArray(StandardCharsets.UTF_8))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun htmlResponse(html: String): Response =
|
||||||
|
Response(200, "text/html; charset=utf-8", html.toByteArray(StandardCharsets.UTF_8))
|
||||||
|
|
||||||
|
private fun readBody(input: InputStream, headers: Map<String, String>): ByteArray {
|
||||||
|
val length = headers["content-length"]?.toLongOrNull() ?: 0L
|
||||||
|
if (length <= 0) return ByteArray(0)
|
||||||
|
require(length <= MAX_BODY) { "请求体过大" }
|
||||||
|
val buffer = ByteArray(length.toInt())
|
||||||
|
var read = 0
|
||||||
|
while (read < buffer.size) {
|
||||||
|
val count = input.read(buffer, read, buffer.size - read)
|
||||||
|
if (count < 0) break
|
||||||
|
read += count
|
||||||
|
}
|
||||||
|
return if (read == buffer.size) buffer else buffer.copyOf(read)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readLine(input: InputStream): String? {
|
||||||
|
val builder = StringBuilder()
|
||||||
|
while (true) {
|
||||||
|
val value = input.read()
|
||||||
|
if (value < 0) return if (builder.isEmpty()) null else builder.toString()
|
||||||
|
if (value == '\n'.code) break
|
||||||
|
if (value != '\r'.code) builder.append(value.toChar())
|
||||||
|
if (builder.length > 8192) break
|
||||||
|
}
|
||||||
|
return builder.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseQuery(raw: String): Map<String, String> {
|
||||||
|
if (raw.isBlank()) return emptyMap()
|
||||||
|
val result = mutableMapOf<String, String>()
|
||||||
|
raw.split('&').forEach { pair ->
|
||||||
|
if (pair.isBlank()) return@forEach
|
||||||
|
val key = pair.substringBefore('=')
|
||||||
|
val value = pair.substringAfter('=', "")
|
||||||
|
result[decode(key)] = decode(value)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decode(value: String): String = try {
|
||||||
|
URLDecoder.decode(value, "UTF-8")
|
||||||
|
} catch (_: Exception) {
|
||||||
|
value
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writeResponse(output: OutputStream, response: Response) {
|
||||||
|
val length = response.file?.length() ?: response.body?.size?.toLong() ?: 0L
|
||||||
|
val header = StringBuilder()
|
||||||
|
.append("HTTP/1.1 ${response.code} ${statusText(response.code)}\r\n")
|
||||||
|
.append("Content-Type: ${response.contentType}\r\n")
|
||||||
|
.append("Content-Length: $length\r\n")
|
||||||
|
.append("Connection: close\r\n")
|
||||||
|
.append("Access-Control-Allow-Origin: *\r\n")
|
||||||
|
response.headers.forEach { (key, value) -> header.append("$key: $value\r\n") }
|
||||||
|
header.append("\r\n")
|
||||||
|
output.write(header.toString().toByteArray(StandardCharsets.UTF_8))
|
||||||
|
if (response.file != null) {
|
||||||
|
FileInputStream(response.file).use { stream -> stream.copyTo(output, 64 * 1024) }
|
||||||
|
} else if (response.body != null && response.body.isNotEmpty()) {
|
||||||
|
output.write(response.body)
|
||||||
|
}
|
||||||
|
output.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun statusText(code: Int): String = when (code) {
|
||||||
|
200 -> "OK"
|
||||||
|
204 -> "No Content"
|
||||||
|
400 -> "Bad Request"
|
||||||
|
403 -> "Forbidden"
|
||||||
|
404 -> "Not Found"
|
||||||
|
else -> "OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Response(
|
||||||
|
val code: Int,
|
||||||
|
val contentType: String,
|
||||||
|
val body: ByteArray? = null,
|
||||||
|
val file: File? = null,
|
||||||
|
val headers: List<Pair<String, String>> = emptyList(),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -8,7 +8,12 @@ import java.security.MessageDigest
|
|||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
class FileService(private val root: File) {
|
class FileService(
|
||||||
|
private val root: File,
|
||||||
|
/** 目录浏览能力;为空时控制通道的 `list` 操作会返回错误。 */
|
||||||
|
private val browser: FileBrowser? = null,
|
||||||
|
) {
|
||||||
|
|
||||||
private data class Entry(
|
private data class Entry(
|
||||||
val id: String,
|
val id: String,
|
||||||
val name: String,
|
val name: String,
|
||||||
@@ -82,6 +87,12 @@ class FileService(private val root: File) {
|
|||||||
sessions.remove(sessionId)
|
sessions.remove(sessionId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 控制通道 msgType=7 的 `op=list`:浏览 Android 文件目录。 */
|
||||||
|
fun list(path: String): String {
|
||||||
|
val current = browser ?: throw IllegalStateException("文件浏览未启用")
|
||||||
|
return current.list(path).toString()
|
||||||
|
}
|
||||||
|
|
||||||
private fun safeName(name: String) = name.replace("/", "_").replace("\\", "_").replace("..", "_")
|
private fun safeName(name: String) = name.replace("/", "_").replace("\\", "_").replace("..", "_")
|
||||||
|
|
||||||
private fun sha256(file: File): String =
|
private fun sha256(file: File): String =
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package com.ttstd.lancast.receiver.file
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Environment
|
||||||
|
import android.provider.Settings
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 存储访问权限封装。
|
||||||
|
*
|
||||||
|
* Android 11+ 想浏览整块外部存储(含其它应用目录)必须拿到「所有文件访问权限」
|
||||||
|
* ([Environment.isExternalStorageManager]);否则只能退回到应用自己的外部私有目录,
|
||||||
|
* 那个目录不需要任何权限,但看不到用户的相册/下载等文件。
|
||||||
|
*/
|
||||||
|
object StorageAccess {
|
||||||
|
|
||||||
|
/** 是否具备「浏览整块外部存储」的能力。 */
|
||||||
|
fun canBrowseAll(context: Context): Boolean =
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
Environment.isExternalStorageManager()
|
||||||
|
} else {
|
||||||
|
hasPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hasPermission(context: Context, permission: String): Boolean =
|
||||||
|
context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
||||||
|
|
||||||
|
/** 运行时权限申请列表:Android 13+ 申请媒体读权限,更早版本申请存储读权限。 */
|
||||||
|
fun runtimePermissions(): Array<String> = when {
|
||||||
|
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> arrayOf(
|
||||||
|
Manifest.permission.READ_MEDIA_IMAGES,
|
||||||
|
Manifest.permission.READ_MEDIA_VIDEO,
|
||||||
|
Manifest.permission.READ_MEDIA_AUDIO,
|
||||||
|
)
|
||||||
|
else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Android 11+ 的「所有文件访问权限」受系统设置页控制,只能跳转授予。 */
|
||||||
|
fun allFilesSettingsIntent(context: Context): Intent? =
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
Intent(
|
||||||
|
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
|
||||||
|
Uri.parse("package:${context.packageName}"),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 可浏览的根目录(按优先级)。 */
|
||||||
|
fun roots(context: Context): List<File> {
|
||||||
|
val result = mutableListOf<File>()
|
||||||
|
if (canBrowseAll(context)) {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val external = Environment.getExternalStorageDirectory()
|
||||||
|
if (external != null && external.exists()) result += external
|
||||||
|
}
|
||||||
|
// 应用外部私有目录始终可读写,作为没有全盘权限时的兜底。
|
||||||
|
context.getExternalFilesDir(null)?.let { result += it }
|
||||||
|
return result.distinctBy { it.absolutePath }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun primaryRoot(context: Context): File? = roots(context).firstOrNull()
|
||||||
|
|
||||||
|
/** 给界面展示的一句话描述。 */
|
||||||
|
fun summary(context: Context): String = when {
|
||||||
|
canBrowseAll(context) ->
|
||||||
|
"已授权访问全部文件,可浏览 /storage/emulated/0"
|
||||||
|
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R ->
|
||||||
|
"未授予「所有文件访问权限」,仅能浏览应用私有目录"
|
||||||
|
else ->
|
||||||
|
"未授予存储读取权限,仅能浏览应用私有目录"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,8 @@ class InputInjector(private val context: Context) {
|
|||||||
is ControlEvent.Wheel -> injectWheel(event)
|
is ControlEvent.Wheel -> injectWheel(event)
|
||||||
is ControlEvent.Clipboard -> injectText(event.text)
|
is ControlEvent.Clipboard -> injectText(event.text)
|
||||||
is ControlEvent.Ping, is ControlEvent.Pong -> Unit
|
is ControlEvent.Ping, is ControlEvent.Pong -> Unit
|
||||||
|
// 投屏请求由 Service 处理,不参与输入注入。
|
||||||
|
is ControlEvent.Mirror -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+48
@@ -10,6 +10,38 @@ sealed class ControlEvent {
|
|||||||
data class Clipboard(val text: String) : ControlEvent()
|
data class Clipboard(val text: String) : ControlEvent()
|
||||||
data class Ping(val timestamp: Long) : ControlEvent()
|
data class Ping(val timestamp: Long) : ControlEvent()
|
||||||
data class Pong(val timestamp: Long) : ControlEvent()
|
data class Pong(val timestamp: Long) : ControlEvent()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 投屏请求 / 应答(msgType = 8)。
|
||||||
|
*
|
||||||
|
* payload = `[action:u8]` + 可选 UTF-8 文本(用于 ERROR/DENIED 的原因说明)。
|
||||||
|
*/
|
||||||
|
data class Mirror(val action: Int, val message: String = "") : ControlEvent()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [ControlEvent.Mirror] 的 action 取值。
|
||||||
|
*
|
||||||
|
* 主控端 → Android:REQUEST / STOP。
|
||||||
|
* Android → 主控端:GRANTED / DENIED / STOPPED / ERROR。
|
||||||
|
*/
|
||||||
|
object MirrorAction {
|
||||||
|
const val REQUEST = 0
|
||||||
|
const val STOP = 1
|
||||||
|
const val GRANTED = 2
|
||||||
|
const val DENIED = 3
|
||||||
|
const val STOPPED = 4
|
||||||
|
const val ERROR = 5
|
||||||
|
|
||||||
|
fun name(action: Int): String = when (action) {
|
||||||
|
REQUEST -> "request"
|
||||||
|
STOP -> "stop"
|
||||||
|
GRANTED -> "granted"
|
||||||
|
DENIED -> "denied"
|
||||||
|
STOPPED -> "stopped"
|
||||||
|
ERROR -> "error"
|
||||||
|
else -> "unknown($action)"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
data class ControlFrame(val version: Int, val sequence: Int, val event: ControlEvent)
|
data class ControlFrame(val version: Int, val sequence: Int, val event: ControlEvent)
|
||||||
@@ -73,6 +105,16 @@ object ControlFrames {
|
|||||||
if (payload.size != 8) return null
|
if (payload.size != 8) return null
|
||||||
ControlEvent.Pong(u64(payload, 0))
|
ControlEvent.Pong(u64(payload, 0))
|
||||||
}
|
}
|
||||||
|
8 -> {
|
||||||
|
if (payload.isEmpty()) return null
|
||||||
|
val action = payload[0].toInt() and 0xff
|
||||||
|
val message = if (payload.size > 1) {
|
||||||
|
String(payload, 1, payload.size - 1, StandardCharsets.UTF_8)
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
ControlEvent.Mirror(action, message)
|
||||||
|
}
|
||||||
else -> return null
|
else -> return null
|
||||||
}
|
}
|
||||||
return ControlFrame(version, sequence, event)
|
return ControlFrame(version, sequence, event)
|
||||||
@@ -95,6 +137,11 @@ object ControlFrames {
|
|||||||
}
|
}
|
||||||
is ControlEvent.Ping -> u64Bytes(event.timestamp)
|
is ControlEvent.Ping -> u64Bytes(event.timestamp)
|
||||||
is ControlEvent.Pong -> u64Bytes(event.timestamp)
|
is ControlEvent.Pong -> u64Bytes(event.timestamp)
|
||||||
|
is ControlEvent.Mirror -> if (event.message.isEmpty()) {
|
||||||
|
byteArrayOf(event.action.toByte())
|
||||||
|
} else {
|
||||||
|
byteArrayOf(event.action.toByte()) + event.message.toByteArray(StandardCharsets.UTF_8)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return byteArrayOf(VERSION.toByte(), msgType(event).toByte()) +
|
return byteArrayOf(VERSION.toByte(), msgType(event).toByte()) +
|
||||||
u16Bytes(sequence) + u32Bytes(payload.size) + payload
|
u16Bytes(sequence) + u32Bytes(payload.size) + payload
|
||||||
@@ -108,6 +155,7 @@ object ControlFrames {
|
|||||||
is ControlEvent.Clipboard -> 4
|
is ControlEvent.Clipboard -> 4
|
||||||
is ControlEvent.Ping -> 5
|
is ControlEvent.Ping -> 5
|
||||||
is ControlEvent.Pong -> 6
|
is ControlEvent.Pong -> 6
|
||||||
|
is ControlEvent.Mirror -> 8
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun u16(bytes: ByteArray, offset: Int) =
|
private fun u16(bytes: ByteArray, offset: Int) =
|
||||||
|
|||||||
+24
@@ -52,6 +52,18 @@ class ReceiverTransport(
|
|||||||
|
|
||||||
val keyEstablished: Boolean get() = keys != null
|
val keyEstablished: Boolean get() = keys != null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 收到主控端投屏请求/停止请求时的回调:(action, message)。
|
||||||
|
* 由 Service 绑定,用于弹窗确认与开流/停流。
|
||||||
|
*/
|
||||||
|
@Volatile
|
||||||
|
var onMirrorEvent: ((Int, String) -> Unit)? = null
|
||||||
|
|
||||||
|
/** 回送投屏应答(GRANTED / DENIED / STOPPED / ERROR)。 */
|
||||||
|
fun sendMirror(action: Int, message: String = "") {
|
||||||
|
sendControl(ControlEvent.Mirror(action, message))
|
||||||
|
}
|
||||||
|
|
||||||
fun start() {
|
fun start() {
|
||||||
if (active) return
|
if (active) return
|
||||||
active = true
|
active = true
|
||||||
@@ -203,6 +215,8 @@ class ReceiverTransport(
|
|||||||
when (val event = frame.event) {
|
when (val event = frame.event) {
|
||||||
is ControlEvent.Clipboard -> clipboard.publish(event.text)
|
is ControlEvent.Clipboard -> clipboard.publish(event.text)
|
||||||
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
|
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
|
||||||
|
is ControlEvent.Pong -> Unit
|
||||||
|
is ControlEvent.Mirror -> onMirrorEvent?.invoke(event.action, event.message)
|
||||||
else -> injector.inject(frame)
|
else -> injector.inject(frame)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,6 +243,16 @@ class ReceiverTransport(
|
|||||||
}
|
}
|
||||||
"progress" -> sendRaw(7, fileService.progress(request.getString("sessionId")))
|
"progress" -> sendRaw(7, fileService.progress(request.getString("sessionId")))
|
||||||
"cancel" -> fileService.cancel(request.getString("sessionId"))
|
"cancel" -> fileService.cancel(request.getString("sessionId"))
|
||||||
|
"list" -> {
|
||||||
|
val json = try {
|
||||||
|
JSONObject(fileService.list(request.optString("path", ""))).put("op", "list")
|
||||||
|
} catch (error: Exception) {
|
||||||
|
JSONObject()
|
||||||
|
.put("op", "list")
|
||||||
|
.put("error", error.message ?: "目录浏览失败")
|
||||||
|
}
|
||||||
|
sendRaw(7, json.toString())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,4 +4,12 @@
|
|||||||
<item name="android:windowBackground">@android:color/background_dark</item>
|
<item name="android:windowBackground">@android:color/background_dark</item>
|
||||||
<item name="android:textColorPrimary">@android:color/white</item>
|
<item name="android:textColorPrimary">@android:color/white</item>
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
<!-- 投屏确认页:半透明对话框样式,不显示标题栏。 -->
|
||||||
|
<style name="Theme.Lancast.Request" parent="@android:style/Theme.Material.Light.Dialog.NoActionBar">
|
||||||
|
<item name="android:windowBackground">@android:color/transparent</item>
|
||||||
|
<item name="android:windowIsTranslucent">true</item>
|
||||||
|
<item name="android:backgroundDimEnabled">true</item>
|
||||||
|
<item name="android:windowNoTitle">true</item>
|
||||||
|
</style>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -155,6 +155,10 @@ class SenderBridge {
|
|||||||
return 4;
|
return 4;
|
||||||
case 'ping':
|
case 'ping':
|
||||||
return 5;
|
return 5;
|
||||||
|
// 投屏请求/停止:被控端会弹窗确认后再开流。
|
||||||
|
case 'requestMirror':
|
||||||
|
case 'stopMirror':
|
||||||
|
return 8;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -199,6 +203,12 @@ class SenderBridge {
|
|||||||
(ts >> 24) & 0xff,
|
(ts >> 24) & 0xff,
|
||||||
0, 0, 0, 0,
|
0, 0, 0, 0,
|
||||||
];
|
];
|
||||||
|
case 'requestMirror':
|
||||||
|
// action=0 请求投屏;可选的 UTF-8 说明跟在后面。
|
||||||
|
return [0, ...(payload['message'] as String? ?? '').codeUnits];
|
||||||
|
case 'stopMirror':
|
||||||
|
// action=1 请求停止投屏。
|
||||||
|
return [1, ...(payload['message'] as String? ?? '').codeUnits];
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,6 +65,18 @@ class ControlToolbar extends StatelessWidget {
|
|||||||
enabled: enabled,
|
enabled: enabled,
|
||||||
onPressed: () => onEvent('clipboard', {'text': 'TTSTD Connect'}),
|
onPressed: () => onEvent('clipboard', {'text': 'TTSTD Connect'}),
|
||||||
),
|
),
|
||||||
|
_Action(
|
||||||
|
icon: Icons.screen_share,
|
||||||
|
label: '请求投屏',
|
||||||
|
enabled: enabled,
|
||||||
|
onPressed: () => onEvent('requestMirror', const {}),
|
||||||
|
),
|
||||||
|
_Action(
|
||||||
|
icon: Icons.stop_screen_share,
|
||||||
|
label: '停止投屏',
|
||||||
|
enabled: enabled,
|
||||||
|
onPressed: () => onEvent('stopMirror', const {}),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use super::codec::{CodecError, ControlFrameCodec, ControlFrameHeader};
|
use super::codec::{CodecError, ControlFrameCodec, ControlFrameHeader};
|
||||||
use super::events::{
|
use super::events::{
|
||||||
ClipboardEvent, ControlEvent, ControlEventKind, KeyAction, KeyboardEvent, MouseAction,
|
ClipboardEvent, ControlEvent, ControlEventKind, KeyAction, KeyboardEvent, MirrorEvent,
|
||||||
MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD, MSG_KEY, MSG_MOUSE, MSG_PING,
|
MouseAction, MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD, MSG_KEY,
|
||||||
MSG_PONG, MSG_TOUCH, MSG_WHEEL, PROTOCOL_VERSION,
|
MSG_MIRROR, MSG_MOUSE, MSG_PING, MSG_PONG, MSG_TOUCH, MSG_WHEEL, PROTOCOL_VERSION,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, Copy)]
|
#[derive(Debug, Default, Clone, Copy)]
|
||||||
@@ -51,6 +51,10 @@ impl ControlFrameCodec for BinaryCodec {
|
|||||||
ControlEventKind::Ping(timestamp) | ControlEventKind::Pong(timestamp) => {
|
ControlEventKind::Ping(timestamp) | ControlEventKind::Pong(timestamp) => {
|
||||||
buffer.extend_from_slice(×tamp.to_le_bytes());
|
buffer.extend_from_slice(×tamp.to_le_bytes());
|
||||||
}
|
}
|
||||||
|
ControlEventKind::Mirror(payload) => {
|
||||||
|
buffer.push(payload.action);
|
||||||
|
buffer.extend_from_slice(payload.message.as_bytes());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let payload_len = (buffer.len() - ControlFrameHeader::LEN) as u32;
|
let payload_len = (buffer.len() - ControlFrameHeader::LEN) as u32;
|
||||||
@@ -149,6 +153,15 @@ fn decode_payload(msg_type: u8, payload: &[u8]) -> Result<ControlEventKind, Code
|
|||||||
Ok(ControlEventKind::Pong(timestamp))
|
Ok(ControlEventKind::Pong(timestamp))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
MSG_MIRROR => {
|
||||||
|
if payload.is_empty() {
|
||||||
|
return Err(CodecError::InvalidPayload("投屏动作负载至少 1 字节"));
|
||||||
|
}
|
||||||
|
let action = payload[0];
|
||||||
|
let message = String::from_utf8(payload[1..].to_vec())
|
||||||
|
.map_err(|_| CodecError::InvalidUtf8)?;
|
||||||
|
Ok(ControlEventKind::Mirror(MirrorEvent { action, message }))
|
||||||
|
}
|
||||||
other => Err(CodecError::UnknownMsgType(other)),
|
other => Err(CodecError::UnknownMsgType(other)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -198,6 +211,14 @@ mod tests {
|
|||||||
}));
|
}));
|
||||||
assert_roundtrip(ControlEventKind::Ping(1_700_000_000_000));
|
assert_roundtrip(ControlEventKind::Ping(1_700_000_000_000));
|
||||||
assert_roundtrip(ControlEventKind::Pong(1_700_000_000_001));
|
assert_roundtrip(ControlEventKind::Pong(1_700_000_000_001));
|
||||||
|
assert_roundtrip(ControlEventKind::Mirror(MirrorEvent {
|
||||||
|
action: 0,
|
||||||
|
message: String::new(),
|
||||||
|
}));
|
||||||
|
assert_roundtrip(ControlEventKind::Mirror(MirrorEvent {
|
||||||
|
action: 5,
|
||||||
|
message: "无屏幕录制权限".to_string(),
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -8,6 +8,19 @@ pub const MSG_CLIPBOARD: u8 = 4;
|
|||||||
pub const MSG_PING: u8 = 5;
|
pub const MSG_PING: u8 = 5;
|
||||||
pub const MSG_PONG: u8 = 6;
|
pub const MSG_PONG: u8 = 6;
|
||||||
|
|
||||||
|
/// 投屏请求/应答。payload = `[action:u8]` + 可选 UTF-8 文本。
|
||||||
|
pub const MSG_MIRROR: u8 = 8;
|
||||||
|
|
||||||
|
/// 投屏控制动作,两端必须保持一致。
|
||||||
|
pub mod mirror_action {
|
||||||
|
pub const REQUEST: u8 = 0;
|
||||||
|
pub const STOP: u8 = 1;
|
||||||
|
pub const GRANTED: u8 = 2;
|
||||||
|
pub const DENIED: u8 = 3;
|
||||||
|
pub const STOPPED: u8 = 4;
|
||||||
|
pub const ERROR: u8 = 5;
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum TouchAction {
|
pub enum TouchAction {
|
||||||
Down,
|
Down,
|
||||||
@@ -138,6 +151,13 @@ pub struct ClipboardEvent {
|
|||||||
pub text: String,
|
pub text: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 投屏请求/应答负载。`message` 用于 DENIED / ERROR 的原因说明。
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct MirrorEvent {
|
||||||
|
pub action: u8,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum ControlEventKind {
|
pub enum ControlEventKind {
|
||||||
Touch(TouchEvent),
|
Touch(TouchEvent),
|
||||||
@@ -147,6 +167,7 @@ pub enum ControlEventKind {
|
|||||||
Clipboard(ClipboardEvent),
|
Clipboard(ClipboardEvent),
|
||||||
Ping(u64),
|
Ping(u64),
|
||||||
Pong(u64),
|
Pong(u64),
|
||||||
|
Mirror(MirrorEvent),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -173,6 +194,7 @@ impl ControlEvent {
|
|||||||
ControlEventKind::Clipboard(_) => MSG_CLIPBOARD,
|
ControlEventKind::Clipboard(_) => MSG_CLIPBOARD,
|
||||||
ControlEventKind::Ping(_) => MSG_PING,
|
ControlEventKind::Ping(_) => MSG_PING,
|
||||||
ControlEventKind::Pong(_) => MSG_PONG,
|
ControlEventKind::Pong(_) => MSG_PONG,
|
||||||
|
ControlEventKind::Mirror(_) => MSG_MIRROR,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,8 +14,8 @@ use std::thread::{self, JoinHandle};
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use crate::control::events::{
|
use crate::control::events::{
|
||||||
ClipboardEvent, KeyAction, KeyboardEvent, MouseAction, MouseEvent, TouchAction, TouchEvent,
|
ClipboardEvent, KeyAction, KeyboardEvent, MirrorEvent, MouseAction, MouseEvent, TouchAction,
|
||||||
WheelEvent,
|
TouchEvent, WheelEvent,
|
||||||
};
|
};
|
||||||
use crate::control::{ControlEvent, ControlEventKind};
|
use crate::control::{ControlEvent, ControlEventKind};
|
||||||
|
|
||||||
@@ -284,6 +284,11 @@ pub fn ping_event(sequence: u16, timestamp: u64) -> ControlEvent {
|
|||||||
ControlEvent::new(sequence, ControlEventKind::Ping(timestamp))
|
ControlEvent::new(sequence, ControlEventKind::Ping(timestamp))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 构造投屏请求/停止事件(主控端 → 被控端)。
|
||||||
|
pub fn mirror_event(sequence: u16, action: u8, message: String) -> ControlEvent {
|
||||||
|
ControlEvent::new(sequence, ControlEventKind::Mirror(MirrorEvent { action, message }))
|
||||||
|
}
|
||||||
|
|
||||||
fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
|
fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
|
||||||
while shared.running.load(Ordering::Relaxed) {
|
while shared.running.load(Ordering::Relaxed) {
|
||||||
match listener.accept() {
|
match listener.accept() {
|
||||||
|
|||||||
@@ -300,6 +300,7 @@ pub unsafe extern "C" fn ttstd_control_decode(
|
|||||||
ControlEventKind::Key(_) => "key",
|
ControlEventKind::Key(_) => "key",
|
||||||
ControlEventKind::Wheel(_) => "wheel",
|
ControlEventKind::Wheel(_) => "wheel",
|
||||||
ControlEventKind::Clipboard(_) => "clipboard",
|
ControlEventKind::Clipboard(_) => "clipboard",
|
||||||
|
ControlEventKind::Mirror(_) => "mirror",
|
||||||
};
|
};
|
||||||
let json = format!(
|
let json = format!(
|
||||||
"{{\"sequence\":{},\"msgType\":{},\"kind\":\"{}\"}}",
|
"{{\"sequence\":{},\"msgType\":{},\"kind\":\"{}\"}}",
|
||||||
@@ -358,6 +359,12 @@ pub unsafe extern "C" fn ttstd_demo_send_control(
|
|||||||
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
|
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
|
||||||
]),
|
]),
|
||||||
)),
|
)),
|
||||||
|
// 8 = 投屏请求/停止:[action:u8] + 可选 UTF-8 说明
|
||||||
|
8 if !bytes.is_empty() => Some(crate::demo_server::mirror_event(
|
||||||
|
sequence,
|
||||||
|
bytes[0],
|
||||||
|
String::from_utf8_lossy(&bytes[1..]).to_string(),
|
||||||
|
)),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
match event {
|
match event {
|
||||||
|
|||||||
Reference in new issue
Block a user