-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPubkyImageCache.kt
More file actions
52 lines (44 loc) · 1.5 KB
/
PubkyImageCache.kt
File metadata and controls
52 lines (44 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package to.bitkit.data
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.File
import java.security.MessageDigest
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PubkyImageCache @Inject constructor(
@ApplicationContext context: Context,
) {
private val memoryCache = ConcurrentHashMap<String, Bitmap>()
private val diskDir: File = File(context.cacheDir, "pubky-images").also { it.mkdirs() }
fun memoryImage(uri: String): Bitmap? = memoryCache[uri]
fun image(uri: String): Bitmap? {
memoryCache[uri]?.let { return it }
val file = diskPath(uri)
if (file.exists()) {
val bitmap = BitmapFactory.decodeFile(file.absolutePath) ?: return null
memoryCache[uri] = bitmap
return bitmap
}
return null
}
fun store(bitmap: Bitmap, data: ByteArray, uri: String) {
memoryCache[uri] = bitmap
runCatching { diskPath(uri).writeBytes(data) }
}
fun clear() {
memoryCache.clear()
runCatching {
diskDir.deleteRecursively()
diskDir.mkdirs()
}
}
private fun diskPath(uri: String): File {
val digest = MessageDigest.getInstance("SHA-256")
val hash = digest.digest(uri.toByteArray()).joinToString("") { "%02x".format(it) }
return File(diskDir, hash)
}
}