49 lines
1.7 KiB
Kotlin
49 lines
1.7 KiB
Kotlin
|
package com.adlerosn.brasilfurfest.schedule.managers
|
||
|
|
||
|
import android.content.Context
|
||
|
import com.adlerosn.brasilfurfest.helper.joinFile
|
||
|
import java.io.File
|
||
|
import java.io.InputStream
|
||
|
import java.io.Serializable
|
||
|
|
||
|
class CacheManager(context: Context): Serializable {
|
||
|
private val cacheLocation = File(context.filesDir, "cache_data")
|
||
|
.also {
|
||
|
if (!it.isDirectory) {
|
||
|
it.mkdirs()
|
||
|
}
|
||
|
}
|
||
|
private val cacheStamps = File(context.filesDir, "cache_stamps")
|
||
|
.also {
|
||
|
if (!it.isDirectory) {
|
||
|
it.mkdirs()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fun getStamp(file: String): String?{
|
||
|
val cachedFile = cacheLocation.joinFile(file)
|
||
|
val cachedData = cacheStamps.joinFile(file)
|
||
|
if(!cachedFile.exists() || !cachedData.exists()) return null
|
||
|
return cachedData.readText().let { if(it.isBlank()) null else it }
|
||
|
}
|
||
|
|
||
|
operator fun get(file: String): Pair<InputStream, String>?{
|
||
|
val cachedFile = cacheLocation.joinFile(file)
|
||
|
val cachedData = cacheStamps.joinFile(file)
|
||
|
if(!cachedFile.exists() || !cachedData.exists()) return null
|
||
|
val stamp = cachedData.readText()
|
||
|
if(stamp.isBlank()) return null
|
||
|
return Pair(
|
||
|
cachedFile.inputStream(),
|
||
|
stamp
|
||
|
)
|
||
|
}
|
||
|
|
||
|
operator fun set(file: String, requestResult: Pair<ByteArray, String>){
|
||
|
if (requestResult.second.isBlank()) return
|
||
|
val cachedFile = cacheLocation.joinFile(file)
|
||
|
val cachedData = cacheStamps.joinFile(file)
|
||
|
cachedData.writeText(requestResult.second)
|
||
|
cachedFile.writeBytes(requestResult.first)
|
||
|
}
|
||
|
}
|