11package io.tolgee.storage
22
33import android.content.Context
4+ import dev.datlag.tooling.canReadSafely
5+ import dev.datlag.tooling.canWriteSafely
6+ import dev.datlag.tooling.existsSafely
7+ import dev.datlag.tooling.mkdirsSafely
8+ import dev.datlag.tooling.scopeCatching
49import java.io.File
510
611class TolgeeStorageProviderAndroid (
7- private val context : Context ,
8- private val versionCode : Int ,
9- private val path : String = " tolgee/localization-cache" ,
12+ private val context : Context ,
13+ private val versionCode : Int ,
14+ private val path : String = " tolgee/localization-cache" ,
1015) : TolgeeStorageProvider {
11- private val cacheDir get() = context.filesDir / path / versionCode.toString()
16+ private val cacheDir get() = context.filesDir / path / versionCode.toString()
1217
13- override fun put (name : String , data : ByteArray ) {
14- val dir = cacheDir
15- dir.mkdirs()
16- val file = dir / escape(name)
17- file.writeBytes(data)
18- }
18+ override fun put (name : String , data : ByteArray ) {
19+ val dir = cacheDir
20+ dir.mkdirsSafely()
21+ val file = dir / escape(name)
22+ if (! file.canWriteSafely()) {
23+ return
24+ }
25+ scopeCatching {
26+ file.writeBytes(data)
27+ }
28+ }
29+
30+ override fun get (name : String ): ByteArray? {
31+ val file = cacheDir / escape(name)
32+ if (! file.existsSafely() || ! file.canReadSafely()) {
33+ return null
34+ }
1935
20- override fun get (name : String ): ByteArray? {
21- val file = cacheDir / escape(name)
22- if (! file.exists()) {
23- return null
36+ return scopeCatching {
37+ file.readBytes()
38+ }.getOrNull()
2439 }
25- return file.readBytes()
26- }
2740
28- private fun escape (name : String ): String {
29- return name.replace(" /" , " _" )
30- }
41+ private fun escape (name : String ): String {
42+ return name.replace(" /" , " _" )
43+ }
3144
32- internal companion object {
33- private infix operator fun File.div (other : String ) = File (this , other)
34- }
45+ internal companion object {
46+ private infix operator fun File.div (other : String ) = File (this , other)
47+ }
3548}
0 commit comments