Do not automatically initialize DefaultVideoMetadataExtractor's data source (#5157)

This will cause a crash for image attachments
This commit is contained in:
Jorge Martin Espinosa 2025-08-12 15:03:43 +02:00 committed by GitHub
parent 539db85e6c
commit dc33a3b2d3

View file

@ -29,7 +29,7 @@ interface VideoMetadataExtractor : AutoCloseable {
@ContributesBinding(AppScope::class) @ContributesBinding(AppScope::class)
class DefaultVideoMetadataExtractor @AssistedInject constructor( class DefaultVideoMetadataExtractor @AssistedInject constructor(
@ApplicationContext context: Context, @ApplicationContext private val context: Context,
@Assisted private val uri: Uri, @Assisted private val uri: Uri,
) : VideoMetadataExtractor { ) : VideoMetadataExtractor {
@ContributesBinding(AppScope::class) @ContributesBinding(AppScope::class)
@ -38,15 +38,16 @@ class DefaultVideoMetadataExtractor @AssistedInject constructor(
override fun create(uri: Uri): DefaultVideoMetadataExtractor override fun create(uri: Uri): DefaultVideoMetadataExtractor
} }
private val mediaMetadataRetriever = MediaMetadataRetriever() // Don't use `by lazy` so we can catch any exceptions thrown during initialization
private val mediaMetadataRetriever = lazy {
init { MediaMetadataRetriever().apply {
mediaMetadataRetriever.setDataSource(context, uri) setDataSource(context, uri)
}
} }
override fun getSize(): Result<Size> = runCatchingExceptions { override fun getSize(): Result<Size> = runCatchingExceptions {
val width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toInt() val width = mediaMetadataRetriever.value.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toInt()
val height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toInt() val height = mediaMetadataRetriever.value.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toInt()
@Suppress("ComplexCondition") @Suppress("ComplexCondition")
if (width != null && width > 0 && height != null && height > 0) { if (width != null && width > 0 && height != null && height > 0) {
@ -57,12 +58,14 @@ class DefaultVideoMetadataExtractor @AssistedInject constructor(
} }
override fun getDuration(): Result<Long> = runCatchingExceptions { override fun getDuration(): Result<Long> = runCatchingExceptions {
mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong() mediaMetadataRetriever.value.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong()
?.takeIf { it > 0L } ?.takeIf { it > 0L }
?: error("Could not retrieve video duration from metadata") ?: error("Could not retrieve video duration from metadata")
} }
override fun close() { override fun close() {
mediaMetadataRetriever.release() if (mediaMetadataRetriever.isInitialized()) {
mediaMetadataRetriever.value.release()
}
} }
} }