From 3436f2169d2495e86d2fb06d0a1ce8d4ea2e8d7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joris=20Pelgr=C3=B6m?= Date: Sun, 14 Aug 2022 02:37:26 +0200 Subject: [PATCH] Use OkHttpClient to download notification videos (#2779) - Change to the OkHttpClient used elsewhere by the app to download notification videos to resolve problems related to cookies and mTLS authentication. As a result, storing and deleting the file is now handled by the app instead of by the system. --- .../android/notifications/MessagingManager.kt | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt b/app/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt index f0b5cb1d3..aaf3de63a 100644 --- a/app/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt +++ b/app/src/main/java/io/homeassistant/companion/android/notifications/MessagingManager.kt @@ -79,6 +79,8 @@ import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request import org.json.JSONObject +import java.io.File +import java.io.FileOutputStream import java.net.URL import java.net.URLDecoder import java.util.Locale @@ -1395,19 +1397,31 @@ class MessagingManager @Inject constructor( Dispatchers.IO ) { url ?: return@withContext null + val videoFile = File(context.applicationContext.cacheDir.absolutePath + "/notifications/video-${System.currentTimeMillis()}") val processingFrames = mutableListOf>() var processingFramesSize = 0 var singleFrame = 0 try { MediaMetadataRetriever().let { mediaRetriever -> + val request = Request.Builder().apply { + url(url) + if (requiresAuth) { + addHeader("Authorization", authenticationUseCase.buildBearerToken()) + } + }.build() + val response = okHttpClient.newCall(request).execute() - if (requiresAuth) { - mediaRetriever.setDataSource(url.toString(), mapOf("Authorization" to authenticationUseCase.buildBearerToken())) - } else { - mediaRetriever.setDataSource(url.toString(), hashMapOf()) + if (!videoFile.exists()) { + videoFile.parentFile?.mkdirs() + videoFile.createNewFile() } + FileOutputStream(videoFile).use { output -> + response.body?.byteStream()?.copyTo(output) + } + response.close() + mediaRetriever.setDataSource(videoFile.absolutePath) val durationInMicroSeconds = ((mediaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: VIDEO_GUESS_MILLISECONDS)) * 1000 // Start at 100 milliseconds and get frames every 0.75 seconds until reaching the end @@ -1435,7 +1449,9 @@ class MessagingManager @Inject constructor( Log.e(TAG, "Couldn't download video for notification", e) } - return@withContext processingFrames.awaitAll().filterNotNull() + val frames = processingFrames.awaitAll().filterNotNull() + videoFile.delete() + return@withContext frames } private fun Bitmap.getCompressedFrame(): Bitmap? {