From 697e457da453568ca703c2b655a2dd490157b443 Mon Sep 17 00:00:00 2001 From: Allan Wang Date: Tue, 25 Dec 2018 16:32:51 -0500 Subject: Clean up image activity and prepare for tests --- .../pitchedapps/frost/activities/ImageActivity.kt | 157 +++++++++------------ 1 file changed, 69 insertions(+), 88 deletions(-) (limited to 'app/src/main/kotlin/com/pitchedapps/frost/activities/ImageActivity.kt') diff --git a/app/src/main/kotlin/com/pitchedapps/frost/activities/ImageActivity.kt b/app/src/main/kotlin/com/pitchedapps/frost/activities/ImageActivity.kt index 83f617ba..bbd0463a 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/activities/ImageActivity.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/activities/ImageActivity.kt @@ -28,13 +28,14 @@ import ca.allanwang.kau.mediapicker.scanMedia import ca.allanwang.kau.permissions.PERMISSION_WRITE_EXTERNAL_STORAGE import ca.allanwang.kau.permissions.kauRequestPermissions import ca.allanwang.kau.utils.colorToForeground +import ca.allanwang.kau.utils.copyFromInputStream import ca.allanwang.kau.utils.fadeOut import ca.allanwang.kau.utils.fadeScaleTransition import ca.allanwang.kau.utils.isHidden +import ca.allanwang.kau.utils.isVisible import ca.allanwang.kau.utils.scaleXY import ca.allanwang.kau.utils.setIcon import ca.allanwang.kau.utils.tint -import ca.allanwang.kau.utils.use import ca.allanwang.kau.utils.withAlpha import ca.allanwang.kau.utils.withMinAlpha import com.davemorrissey.labs.subscaleview.ImageSource @@ -53,7 +54,6 @@ import com.pitchedapps.frost.utils.ARG_IMAGE_URL import com.pitchedapps.frost.utils.ARG_TEXT import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.utils.Prefs -import com.pitchedapps.frost.utils.createFreshFile import com.pitchedapps.frost.utils.frostSnackbar import com.pitchedapps.frost.utils.frostUriFromFile import com.pitchedapps.frost.utils.isIndirectImageUrl @@ -63,10 +63,11 @@ import com.pitchedapps.frost.utils.sendFrostEmail import com.pitchedapps.frost.utils.setFrostColors import com.sothree.slidinguppanel.SlidingUpPanelLayout import kotlinx.android.synthetic.main.activity_image.* +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import okhttp3.Response -import org.jetbrains.anko.activityUiThreadWithContext -import org.jetbrains.anko.doAsync -import org.jetbrains.anko.uiThread import java.io.File import java.io.FileFilter import java.io.IOException @@ -79,6 +80,7 @@ import java.util.Locale */ class ImageActivity : KauBaseActivity() { + @Volatile internal var errorRef: Throwable? = null private lateinit var tempDir: File @@ -138,6 +140,16 @@ class ImageActivity : KauBaseActivity() { )}_${Math.abs(imageUrl.hashCode())}" } + private fun loadError(e: Throwable) { + errorRef = e + e.logFrostEvent("Image load error") + L.e { "Failed to load image $imageHash" } + if (image_progress.isVisible) + image_progress.fadeOut() + tempFile.delete() + fabAction = FabStates.ERROR + } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent?.extras ?: return finish() @@ -165,12 +177,8 @@ class ImageActivity : KauBaseActivity() { }) image_fab.setOnClickListener { fabAction.onClick(this) } image_photo.setOnImageEventListener(object : SubsamplingScaleImageView.DefaultOnImageEventListener() { - override fun onImageLoadError(e: Exception?) { - errorRef = e - e.logFrostEvent("Image load error") - L.e { "Failed to load image $imageUrl" } - tempFile?.delete() - fabAction = FabStates.ERROR + override fun onImageLoadError(e: Exception) { + loadError(e) } }) setFrostColors { @@ -178,69 +186,15 @@ class ImageActivity : KauBaseActivity() { } tempDir = File(cacheDir, IMAGE_FOLDER) tempFile = File(tempDir, imageHash) - doAsync({ - L.e(it) { "Failed to load image $imageHash" } - errorRef = it - runOnUiThread { image_progress.fadeOut() } - tempFile.delete() - fabAction = FabStates.ERROR - }) { - val loaded = loadImage(tempFile) - uiThread { - image_progress.fadeOut() - if (!loaded) { - fabAction = FabStates.ERROR - } else { - image_photo.setImage(ImageSource.uri(frostUriFromFile(tempFile))) - fabAction = FabStates.DOWNLOAD - image_photo.animate().alpha(1f).scaleXY(1f).start() - } - } + launch(CoroutineExceptionHandler { _, err -> loadError(err) }) { + downloadImageTo(tempFile) + image_progress.fadeOut() + image_photo.setImage(ImageSource.uri(frostUriFromFile(tempFile))) + fabAction = FabStates.DOWNLOAD + image_photo.animate().alpha(1f).scaleXY(1f).start() } } - /** - * Attempts to load the image to [file] - * Returns true if successful - * Note that this is a long execution and should not be done on the UI thread - */ - private fun loadImage(file: File): Boolean { - if (file.exists() && file.length() > 1) { - file.setLastModified(System.currentTimeMillis()) - L.d { "Loading from local cache ${file.absolutePath}" } - return true - } - val response = getImageResponse() - - if (!response.isSuccessful) { - L.e { "Unsuccessful response for image" } - errorRef = Throwable("Unsuccessful response for image") - return false - } - - if (!file.createFreshFile()) { - L.e { "Could not create temp file" } - return false - } - - var valid = false - - response.body()?.byteStream()?.use { input -> - file.outputStream().use { output -> - input.copyTo(output) - valid = true - } - } - - if (!valid) { - L.e { "Failed to copy file" } - file.delete() - return false - } - - return true - } - @Throws(IOException::class) private fun createPublicMediaFile(): File { val timeStamp = SimpleDateFormat(TIME_FORMAT, Locale.getDefault()).format(Date()) @@ -257,30 +211,59 @@ class ImageActivity : KauBaseActivity() { .call() .execute() + /** + * Saves the image to the specified file, creating it if it doesn't exist. + * Returns true if a change is made, false otherwise. + * Throws an error if something goes wrong. + */ @Throws(IOException::class) - private fun downloadImageTo(file: File) { - val body = getImageResponse().body() - ?: throw IOException("Failed to retrieve image body") - body.byteStream().use { input -> - file.outputStream().use { output -> - input.copyTo(output) + private suspend fun downloadImageTo(file: File): Boolean { + val exceptionHandler = CoroutineExceptionHandler { _, _ -> + if (file.isFile && file.length() == 0L) { + file.delete() } } + return withContext(Dispatchers.IO + exceptionHandler) { + if (!file.isFile) { + file.mkdirs() + file.createNewFile() + } + + file.setLastModified(System.currentTimeMillis()) + + // Forbid overwrites + if (file.length() > 1) + return@withContext false + if (tempFile.isFile && tempFile.length() > 1) { + if (tempFile == file) + return@withContext false + tempFile.copyTo(file) + return@withContext true + } + // No temp file, download ourselves + val response = getImageResponse() + + if (!response.isSuccessful) { + throw IOException("Unsuccessful response for image: ${response.peekBody(128).string()}") + } + + val body = response.body() ?: throw IOException("Failed to retrieve image body") + + file.copyFromInputStream(body.byteStream()) + + return@withContext true + } } internal fun saveImage() { kauRequestPermissions(PERMISSION_WRITE_EXTERNAL_STORAGE) { granted, _ -> L.d { "Download image callback granted: $granted" } if (granted) { - doAsync { + launch { val destination = createPublicMediaFile() var success = true try { - val temp = tempFile - if (temp != null) - temp.copyTo(destination, true) - else - downloadImageTo(destination) + downloadImageTo(destination) } catch (e: Exception) { errorRef = e success = false @@ -295,11 +278,9 @@ class ImageActivity : KauBaseActivity() { } catch (ignore: Exception) { } } - activityUiThreadWithContext { - val text = if (success) R.string.image_download_success else R.string.image_download_fail - frostSnackbar(text) - if (success) fabAction = FabStates.SHARE - } + val text = if (success) R.string.image_download_success else R.string.image_download_fail + frostSnackbar(text) + if (success) fabAction = FabStates.SHARE } } } -- cgit v1.2.3