Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.SystemClock
import android.provider.MediaStore
import android.provider.OpenableColumns
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
Expand All @@ -27,57 +29,82 @@ class SharedImageDeviceTest {
/** 走真实 ACTION_SEND、系统内容 URI 和生产 Activity,确认图片只进私有草稿,不自动启动任务。 */
@Test
fun imageShareBecomesPrivateDraftWithoutStartingTask() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val target = instrumentation.targetContext
val app = target.applicationContext as MikaApp
val encoded = ByteArrayOutputStream()
val bitmap = Bitmap.createBitmap(2, 3, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.rgb(36, 102, 180)) }
assertTrue(bitmap.compress(Bitmap.CompressFormat.PNG, 100, encoded))
bitmap.recycle()
val bytes = encoded.toByteArray()
checkFileShare(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "photo.png", "image/png", bytes, "图片分享草稿验证", photo = true)
}

@Test
fun pdfSharedViaClipDataKeepsItsNameAndCaption() {
checkFileShare(MediaStore.Downloads.EXTERNAL_CONTENT_URI, "会议记录.pdf", "application/pdf",
"%PDF-1.7\n%%EOF".toByteArray(), "请总结会议记录", clipOnly = true)
}

@Test
fun plainTextFileWithoutCaptionIsAnAttachment() {
checkFileShare(MediaStore.Downloads.EXTERNAL_CONTENT_URI, "清单.txt", "text/plain", "第一项".toByteArray(), "")
}

private fun checkFileShare(collection: Uri, name: String, mime: String, bytes: ByteArray, text: String,
photo: Boolean = false, clipOnly: Boolean = false) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val target = instrumentation.targetContext
val app = target.applicationContext as MikaApp
val resolver = target.contentResolver
val displayName = "mika-${SystemClock.elapsedRealtimeNanos()}-$name"
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, "mika-share-${SystemClock.uptimeMillis()}.png")
put(MediaStore.Images.Media.MIME_TYPE, "image/png")
put(MediaStore.Images.Media.IS_PENDING, 1)
put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
put(MediaStore.MediaColumns.MIME_TYPE, mime)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
val uri = requireNotNull(resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values))
val uri = requireNotNull(resolver.insert(collection, values))
try {
resolver.openOutputStream(uri, "w")!!.use { it.write(bytes) }
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
val text = "图片分享草稿验证"
resolver.update(uri, ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) }, null, null)
val intent = Intent(Intent.ACTION_SEND).apply {
setClassName(target.packageName, MainActivity::class.java.name)
type = "image/png"
putExtra(Intent.EXTRA_TEXT, text)
putExtra(Intent.EXTRA_STREAM, uri)
// 普通分享方会把 EXTRA_STREAM 迁到 ClipData;显式设置后不依赖 adb am 的额外行为。
clipData = ClipData.newRawUri("shared image", uri)
setPackage(target.packageName)
type = mime
if (text.isNotEmpty()) putExtra(Intent.EXTRA_TEXT, text)
if (!clipOnly) putExtra(Intent.EXTRA_STREAM, uri)
clipData = ClipData.newRawUri(displayName, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
assertEquals(MainActivity::class.java.name, intent.resolveActivity(target.packageManager)?.className)
val runsBefore = app.taskState.runs.value.map { it.runId.value }.toSet()
var received: SharedDraft? = null
val scenario = ActivityScenario.launch<MainActivity>(intent)
try {
val deadline = SystemClock.uptimeMillis() + 15_000
while (SystemClock.uptimeMillis() < deadline) {
instrumentation.waitForIdleSync()
received = app.sharedDrafts.read()?.takeIf { it.text == text && it.image != null }
received = app.sharedDrafts.readAll().firstOrNull { it.attachment?.name == displayName }
if (received != null) break
SystemClock.sleep(100)
}
assertNotNull("The production activity did not save the shared image draft", received)
assertNotNull("The production activity did not save the $mime draft", received)
val draft = requireNotNull(received)
val image = requireNotNull(draft.image)
assertEquals(bytes.size.toLong(), image.size)
val privateCopy = requireNotNull(app.sharedDrafts.imageFile(image.fileName))
assertEquals(text, draft.text)
val attachment = requireNotNull(draft.attachment)
assertEquals(photo, attachment.photo)
assertEquals(bytes.size.toLong(), attachment.size)
val privateCopy = requireNotNull(app.sharedDrafts.attachmentFile(attachment.fileName))
assertArrayEquals(bytes, privateCopy.readBytes())
val tray = app.chat.ui.value.attachments.single()
assertEquals(photo, tray.photo)
val trayUri = Uri.parse(tray.uri)
resolver.query(trayUri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)!!.use {
assertTrue(it.moveToFirst())
assertEquals(displayName, it.getString(0))
}
val draftDir = File(target.filesDir, "shared-drafts").canonicalFile
assertTrue(privateCopy.canonicalFile.toPath().startsWith(draftDir.toPath()))
assertEquals("Sharing a draft must not start a task", runsBefore,
app.taskState.runs.value.map { it.runId.value }.toSet())
} finally {
app.sharedDrafts.read()?.takeIf { it.text == text }?.let { app.sharedDrafts.clear(it.conversationId) }
received?.let { app.sharedDrafts.clear(it.conversationId) }
runCatching { scenario.onActivity { it.finish() } }
}
} finally {
Expand Down
9 changes: 2 additions & 7 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -143,16 +143,11 @@
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- 系统分享只进入现有对话页的草稿;文字、链接或一张内容图片都不会自动执行。 -->
<!-- 系统分享的文字、链接或单个文件先进对话草稿。 -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>

Expand Down
10 changes: 6 additions & 4 deletions app/src/main/java/com/wangzan101/mika/MikaApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ class MikaApp : Application(), WebOwner, SandboxOwner, TaskEnvironment.Owner, Ph
/** 对话编号到工作区的解析器(不依赖 [chat] 避免循环 lazy)。 */
val workspaceResolver: WorkspaceResolver by lazy { WorkspaceResolver(conversations, projects) }

/** 最近一次系统分享尚未发送的草稿和它的私有图片副本。 */
/** 系统分享尚未发送的草稿和它的私有附件副本。 */
val sharedDrafts: SharedDraftStore by lazy { SharedDraftStore(java.io.File(filesDir, "shared-drafts")) }

/** 用户自己打开的终端(按工作区):只从界面进,不交给任何任务,也不写运行记录。 */
Expand Down Expand Up @@ -536,9 +536,11 @@ class MikaApp : Application(), WebOwner, SandboxOwner, TaskEnvironment.Owner, Ph
// 标题后面加当前界面语言的「分支」后缀;源标题太长时先截短,后缀留着
branchTitle = { base -> ChatCopy.branchTitle(base, tr(R.string.chat_branch_title_suffix)) },
sharedDrafts = sharedDrafts,
sharedDraftUri = { name ->
sharedDrafts.imageFile(name)?.let { file ->
androidx.core.content.FileProvider.getUriForFile(app, com.wangzan101.mika.chat.AttachFilesProvider.authority(app.packageName), file).toString()
sharedDraftUri = { attachment ->
sharedDrafts.attachmentFile(attachment.fileName)?.let { file ->
androidx.core.content.FileProvider.getUriForFile(
app, com.wangzan101.mika.chat.AttachFilesProvider.authority(app.packageName), file, attachment.name,
).toString()
}.orEmpty()
},
teaching = { teach.blocksTasks() },
Expand Down
82 changes: 42 additions & 40 deletions app/src/main/java/com/wangzan101/mika/chat/SharedDraftImporter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,65 +16,63 @@ import java.io.File
import java.io.InputStream
import java.util.UUID

/** 把系统分享的一张内容图片立即复制到私有草稿目录,不依赖之后仍有效的 URI 授权。 */
/** 把系统分享的文件复制到私有草稿目录,不依赖之后仍有效的 URI 授权。 */
class SharedDraftImporter(private val context: Context, private val store: SharedDraftStore) {
suspend fun image(text: String, uri: Uri, declaredType: String?): SharedDraft? {
suspend fun attachment(text: String, uri: Uri, declaredType: String?): SharedDraft? {
var copied: File? = null
return try {
withContext(Dispatchers.IO) {
if (text.length > SharedDraftStore.MAX_TEXT_CHARS || declaredType?.startsWith("image/") != true) return@withContext null
if (text.length > SharedDraftStore.MAX_TEXT_CHARS) return@withContext null
if (uri.scheme != ContentResolver.SCHEME_CONTENT) return@withContext null
// 外部分享不应该借 Mika 自己的私有 provider 指定另一个内部文件;所有收到的内容都从外部 provider 新复制。
val authority = uri.authority.orEmpty()
if (authority == context.packageName || authority.startsWith("${context.packageName}.")) return@withContext null
// Android 跨用户 URI 的 authority 可以是「用户编号@提供方」。
val authority = uri.authority.orEmpty().substringAfterLast('@')
if (authority.isBlank() || authority == context.packageName || authority.startsWith("${context.packageName}.")) return@withContext null
if (uri.path?.split('/')?.any { it == ".." } == true) return@withContext null
val resolver = context.contentResolver
val mime = runCatching { resolver.getType(uri) }.getOrNull() ?: declaredType
if (!mime.startsWith("image/")) return@withContext null
val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime)
?.filter { it.isLetterOrDigit() }?.takeIf { it.isNotEmpty() } ?: "img"
val providerType = runCatching { resolver.getType(uri) }.getOrNull()?.substringBefore(';')?.trim()?.lowercase()
var display: String? = null
var declaredSize = -1L
runCatching {
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
if (c.moveToFirst()) {
display = c.getString(0)
if (!c.isNull(1)) declaredSize = c.getLong(1)
val nameColumn = c.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeColumn = c.getColumnIndex(OpenableColumns.SIZE)
if (nameColumn >= 0) display = c.getString(nameColumn)
if (sizeColumn >= 0 && !c.isNull(sizeColumn)) declaredSize = c.getLong(sizeColumn)
}
}
}
if (declaredSize > Attachments.MAX_BYTES) return@withContext null
val name = Attachments.safeName(display ?: "image.$extension")
val mimeMap = MimeTypeMap.getSingleton()
val sourceName = display?.takeIf { it.isNotBlank() }
?: uri.lastPathSegment?.substringAfterLast('/')?.takeIf { '.' in it }
val suffix = sourceName?.substringAfterLast('.', "")?.lowercase()?.takeIf { it.matches(EXTENSION) }
val mime = listOfNotNull(providerType, declaredType).firstOrNull {
it.contains('/') && '*' !in it && it != "application/octet-stream"
} ?: suffix?.let { mimeMap.getMimeTypeFromExtension(it) }
val photo = mime?.startsWith("image/") == true || declaredType?.startsWith("image/") == true ||
providerType?.startsWith("image/") == true
if (photo && mime != null && !mime.startsWith("image/")) return@withContext null
val extension = mime?.let { mimeMap.getExtensionFromMimeType(it) }?.takeIf { it.matches(EXTENSION) }
?: suffix ?: if (photo) "img" else "bin"
val fallbackName = if (photo) "image.$extension" else "attachment.$extension"
val name = Attachments.safeName(sourceName ?: fallbackName)
val fileName = "${UUID.randomUUID()}.$extension"
val final = store.imageFile(fileName) ?: return@withContext null
val final = store.attachmentFile(fileName) ?: return@withContext null
copied = final
val tmp = store.imageFile("$fileName.tmp") ?: return@withContext null
val size = try {
resolver.openInputStream(uri)?.use { input ->
// 目标文件尚未创建,查它的可用空间会得到 0;copy 会先建好父目录。
SharedDraftCopy.copy(input, tmp, final) { tmp.parentFile?.usableSpace ?: 0L }
} ?: return@withContext null
} catch (e: CancellationException) {
tmp.delete()
final.delete()
throw e
} catch (e: Exception) {
tmp.delete()
final.delete()
return@withContext null
}
// 类型声明可以被伪造;只收系统能识别出边界的位图,不在界面线程解全图。
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
val readable = try {
val tmp = store.attachmentFile("$fileName.tmp") ?: return@withContext null
val size = resolver.openInputStream(uri)?.use { input ->
SharedDraftCopy.copy(input, tmp, final) { tmp.parentFile?.usableSpace ?: 0L }
} ?: return@withContext null
if (photo) {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
final.inputStream().use { BitmapFactory.decodeStream(it, null, bounds) }
bounds.outWidth > 0 && bounds.outHeight > 0
} catch (e: Exception) {
false
}
if (!readable) {
final.delete()
return@withContext null
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
final.delete()
return@withContext null
}
}
SharedDraft("", text, SharedDraftImage(fileName, name, size))
SharedDraft("", text, SharedDraftAttachment(fileName, name, size, photo))
}
} catch (e: CancellationException) {
// withContext 在复制刚完成、结果尚未交给界面的那一刻也可能被取消;这份副本还没绑到草稿,不能留下。
Expand All @@ -85,6 +83,10 @@ class SharedDraftImporter(private val context: Context, private val store: Share
null
}
}

private companion object {
val EXTENSION = Regex("[a-z0-9]{1,16}")
}
}

/** 有界复制:每个块都检查取消和空间;失败或取消时不留下半份临时文件。 */
Expand Down
Loading
Loading