Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add image caching to SmallImageCard #319

Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import com.adobe.marketing.mobile.aepcomposeui.UIAction
import com.adobe.marketing.mobile.aepcomposeui.UIEvent
import com.adobe.marketing.mobile.aepcomposeui.observers.AepUIEventObserver
import com.adobe.marketing.mobile.aepcomposeui.style.SmallImageUIStyle
import com.adobe.marketing.mobile.aepcomposeui.utils.UIUtils
import com.adobe.marketing.mobile.messaging.ContentCardImageManager

/**
* Composable function that renders a small image card UI.
Expand All @@ -58,13 +58,14 @@ fun SmallImageCard(
if (imageUrl.isNullOrBlank()) {
isLoading = false
} else {
UIUtils.downloadImage(imageUrl) {
ContentCardImageManager.getContentCardImageBitmap(imageUrl) {
it.onSuccess { bitmap ->
imageBitmap = bitmap
isLoading = false
}
it.onFailure {
// TODO once we have a default image, we can use that here
// todo - confirm default image bitmap to be used here
// imageBitmap = contentCardManager.getDefaultImageBitmap()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this function can also be added to the companion object so it can be called statically.

isLoading = false
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
Copyright 2024 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

package com.adobe.marketing.mobile.messaging

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.adobe.marketing.mobile.aepcomposeui.utils.UIUtils
import com.adobe.marketing.mobile.messaging.MessagingConstants.CACHE_EXPIRY_TIME
import com.adobe.marketing.mobile.messaging.MessagingConstants.CONTENT_CARD_CACHE_SUBDIRECTORY
import com.adobe.marketing.mobile.services.Log
import com.adobe.marketing.mobile.services.ServiceProvider
import com.adobe.marketing.mobile.services.caching.CacheEntry
import com.adobe.marketing.mobile.services.caching.CacheExpiry
import com.adobe.marketing.mobile.services.caching.CacheResult
import com.adobe.marketing.mobile.services.caching.CacheService
import java.io.InputStream
import java.nio.ByteBuffer

class ContentCardImageManager {

Check warning on line 28 in code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt

View check run for this annotation

Codecov / codecov/patch

code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt#L28

Added line #L28 was not covered by tests

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whole class can be made as an object instead of class, and we can remove the companion object.

companion object {
private val SELF_TAG: String = "ContentCardManager"
private val cacheService: CacheService? = ServiceProvider.getInstance().cacheService
private val defaultCacheName: String = CONTENT_CARD_CACHE_SUBDIRECTORY

/**
* Fetches the image from cache if present in cache, else downloads the image from the given URL and caches it for future calls.
*
* @param imageUrl the url of the image to be fetched
* @param cacheName(optional) the name of the cache for fetching or caching the image, default value used if cache name is not provided
* @param completion is a completion callback. Result.success() method is invoked with the image bitmap fetched. In case of any failure, Result.failure() method is invoked with a throwable
* */
fun getContentCardImageBitmap(imageUrl: String, cacheName: String? = defaultCacheName, completion: (Result<Bitmap>) -> Unit) {
val resolvedCacheName: String = cacheName ?: defaultCacheName
if (isImageCached(imageUrl, resolvedCacheName)) {
getImageBitmapFromCache(imageUrl, resolvedCacheName, completion)
} else {
downloadAndCacheImageBitmap(imageUrl, resolvedCacheName, completion)
}
}

/**
* Checks whether the image at given url is present in the cache or not.
*
* @param imageUrl the url of the image
* @param cacheName the name of the cache for fetching or caching the image
* @return `True` if the image is found in cache, `False` otherwise
* */
private fun isImageCached(imageUrl: String, cacheName: String): Boolean {
val cacheValue = cacheService?.get(cacheName, imageUrl)
return cacheValue != null
}

/**
* Fetches the image from the cache.
*
* @param imageUrl the url of the image to be fetched
* @param cacheName the name of the cache for fetching the image
* @param completion is a completion callback. Result.success() method is invoked with the image bitmap fetched. In case of any failure, Result.failure() method is invoked with a throwable
* */
private fun getImageBitmapFromCache(imageUrl: String, cacheName: String, completion: (Result<Bitmap>) -> Unit) {
val cachedImageBitmap: CacheResult? = cacheService?.get(cacheName, imageUrl)
val inputStream = cachedImageBitmap?.data

// Convert the InputStream to a Bitmap
if (inputStream != null) {
try {
completion(Result.success(BitmapFactory.decodeStream(inputStream)))
} catch (e: Exception) {
Log.warning(
MessagingConstants.LOG_TAG,
SELF_TAG,
"getImageBitmapFromCache - Unable to read cached data into a bitmap due to error: $e"

Check warning on line 81 in code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt

View check run for this annotation

Codecov / codecov/patch

code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt#L77-L81

Added lines #L77 - L81 were not covered by tests
)
completion(Result.failure(e))

Check warning on line 83 in code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt

View check run for this annotation

Codecov / codecov/patch

code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt#L83

Added line #L83 was not covered by tests
}
} else {
Log.warning(
MessagingConstants.LOG_TAG,
SELF_TAG,
"getImageBitmapFromCache - Unable to read cached data as the inputStream is null"

Check warning on line 89 in code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt

View check run for this annotation

Codecov / codecov/patch

code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt#L86-L89

Added lines #L86 - L89 were not covered by tests
)
completion(Result.failure(Exception("Unable to read cached bitmap data as the inputStream is null for the url: $imageUrl, cacheName: $cacheName")))

Check warning on line 91 in code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt

View check run for this annotation

Codecov / codecov/patch

code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt#L91

Added line #L91 was not covered by tests
}
}

/**
* Downloads the image from the given url and caches it.
*
* @param imageUrl the url of the image to be downloaded
* @param completion is a completion callback. Result.success() method is invoked with the image bitmap downloaded. In case of any failure, Result.failure() method is invoked with a throwable
* */
private fun downloadAndCacheImageBitmap(imageUrl: String, cacheName: String, completion: (Result<Bitmap>) -> Unit) {
UIUtils.downloadImage(imageUrl) {
it.onSuccess { bitmap ->
val isImageCacheSuccessful = cacheImage(bitmap, imageUrl, cacheName)
if (!isImageCacheSuccessful) {
Log.warning(
MessagingConstants.LOG_TAG,
SELF_TAG,
"downloadAndCacheImageBitmap - Image downloaded but failed to cache the image from url: $imageUrl"

Check warning on line 109 in code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt

View check run for this annotation

Codecov / codecov/patch

code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt#L106-L109

Added lines #L106 - L109 were not covered by tests
)
}
completion(Result.success(bitmap))
}
it.onFailure { failure ->
Log.warning(
MessagingConstants.LOG_TAG,
SELF_TAG,
"downloadAndCacheImageBitmap - Unable to download image from url: $imageUrl"
)
completion(Result.failure(failure))
}
}
}

/**
* Caches the given image.
*
* @param imageBitmap image to be cached
* @param imageName the unique `key` for storing the image in cache
* @param cacheName name of the cache where cache entry is to be created
*
* @return `True` if image is caches successfully, `False` otherwise
* */
private fun cacheImage(imageBitmap: Bitmap, imageName: String, cacheName: String): Boolean {
try {
val imageInputStream: InputStream = imageBitmap.let { bitmap ->
val byteArray = ByteArray(bitmap.byteCount)
val buffer = ByteBuffer.wrap(byteArray)
bitmap.copyPixelsToBuffer(buffer)
buffer.rewind() // Reset the buffer position to the beginning
byteArray.inputStream() // Create InputStream from byte array
}

val cacheEntry = CacheEntry(imageInputStream, CacheExpiry.after(CACHE_EXPIRY_TIME), null)
cacheService?.set(cacheName, imageName, cacheEntry)

return true
} catch (e: Exception) {
Log.warning(
MessagingConstants.LOG_TAG,
SELF_TAG,
"cacheImage - An unexpected error occurred while caching the downloaded image: \n ${e.localizedMessage}"

Check warning on line 152 in code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt

View check run for this annotation

Codecov / codecov/patch

code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt#L148-L152

Added lines #L148 - L152 were not covered by tests
)
return false

Check warning on line 154 in code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt

View check run for this annotation

Codecov / codecov/patch

code/messaging/src/main/java/com/adobe/marketing/mobile/messaging/ContentCardImageManager.kt#L154

Added line #L154 was not covered by tests
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ public final class MessagingConstants {
static final String CACHE_BASE_DIR = "messaging";
static final String PROPOSITIONS_CACHE_SUBDIRECTORY = "propositions";
static final String IMAGES_CACHE_SUBDIRECTORY = "images";
static final String CONTENT_CARD_CACHE_SUBDIRECTORY = "contentCardImages";
static final String HTTP_HEADER_IF_MODIFIED_SINCE = "If-Modified-Since";
static final String HTTP_HEADER_LAST_MODIFIED = "Last-Modified";
static final String HTTP_HEADER_IF_NONE_MATCH = "If-None-Match";
static final String HTTP_HEADER_ETAG = "Etag";
static final int DEFAULT_TIMEOUT = 5;
static final long RESPONSE_CALLBACK_TIMEOUT = 10000; // 10 seconds
static final long CACHE_EXPIRY_TIME = 604800000; // 7 days in milliseconds

private MessagingConstants() {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import com.adobe.marketing.mobile.messaging.R
import com.adobe.marketing.mobile.services.NetworkCallback
import com.adobe.marketing.mobile.services.Networking
import com.adobe.marketing.mobile.services.ServiceProvider
import com.adobe.marketing.mobile.services.caching.CacheService
import com.example.compose.TestTheme
import com.github.takahirom.roborazzi.captureRoboImage
import org.junit.After
Expand All @@ -74,13 +75,15 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockedStatic
import org.mockito.Mockito
import org.mockito.Mockito.any
import org.mockito.Mockito.mockStatic
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.whenever
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
Expand Down Expand Up @@ -433,11 +436,49 @@ class SmallImageCardBehaviorTests {
@Mock
private lateinit var mockAepUIEventObserver: AepUIEventObserver

@Mock
private lateinit var mockCacheService: CacheService
@Mock
private lateinit var mockServiceProvider: ServiceProvider
private lateinit var mockedStaticServiceProvider: MockedStatic<ServiceProvider>

@Mock
private lateinit var mockNetworkService: Networking

@Before
fun setUp() {

MockitoAnnotations.openMocks(this)
mockedStaticServiceProvider = mockStatic(ServiceProvider::class.java)
mockedStaticServiceProvider.`when`<Any> { ServiceProvider.getInstance() }.thenReturn(mockServiceProvider)

whenever(
mockCacheService.set(
org.mockito.kotlin.any(),
org.mockito.kotlin.any(),
org.mockito.kotlin.any()
)
).thenReturn(true)

// Mocking Cache to bypass cache check
whenever(
mockCacheService.get(
org.mockito.kotlin.any(),
org.mockito.kotlin.any()
)
).thenReturn(null)

`when`(mockServiceProvider.networkService).thenReturn(mockNetworkService)

MockitoAnnotations.openMocks(this)
}

@After
fun tearDown() {
mockedStaticServiceProvider.close()
Mockito.validateMockitoUsage()
}

@Test
fun `Test SmallImageCard card click behavior`() {
// setup
Expand Down
Loading
Loading