@@ -17,6 +17,7 @@ import com.lagradost.cloudstream3.mvvm.Resource
1717import com.lagradost.cloudstream3.mvvm.logError
1818import com.lagradost.cloudstream3.mvvm.safeApiCall
1919import com.lagradost.cloudstream3.newSearchResponseList
20+ import com.lagradost.cloudstream3.CloudStreamApp
2021import com.lagradost.cloudstream3.utils.DataStoreHelper
2122import com.lagradost.cloudstream3.utils.Coroutines.atomicListOf
2223import com.lagradost.cloudstream3.utils.ExtractorLink
@@ -69,6 +70,7 @@ class APIRepository(val api: MainAPI) {
6970 private val homeCache = atomicListOf<SavedHomePageResponse >()
7071 private var homeCacheIndex: Int = 0
7172 const val HOME_CACHE_SIZE = 20
73+ const val HOME_CACHE_FOLDER = " home_cache"
7274
7375 fun getTimeout (desired : Long? ): Long {
7476 return (desired ? : DEFAULT_TIMEOUT ).coerceIn(MIN_TIMEOUT , MAX_TIMEOUT )
@@ -77,6 +79,20 @@ class APIRepository(val api: MainAPI) {
7779 fun clearCache () {
7880 cache.clear()
7981 homeCache.clear()
82+ CloudStreamApp .removeKeys(HOME_CACHE_FOLDER )
83+ }
84+
85+ fun hasHomePageCache (apiName : String , page : Int = 1, nameIndex : Int? = null): Boolean {
86+ if (! DataStoreHelper .isCacheEnabled) return false
87+ val lookingForHash = Pair (apiName, Pair (page, nameIndex))
88+ val cacheTtl = DataStoreHelper .cacheTimeSeconds
89+ val inRam = homeCache.withLock {
90+ homeCache.any { it.hash == lookingForHash && unixTime - it.unixTime < cacheTtl }
91+ }
92+ if (inRam) return true
93+ val diskKey = " ${apiName} _${page} _${nameIndex} "
94+ val onDisk = CloudStreamApp .getKey<SavedHomePageResponse >(HOME_CACHE_FOLDER , diskKey)
95+ return onDisk != null && unixTime - onDisk.unixTime < cacheTtl
8096 }
8197 }
8298
@@ -179,6 +195,7 @@ class APIRepository(val api: MainAPI) {
179195 val lookingForHash = Pair (api.name, Pair (page, nameIndex))
180196 val cacheTtl = DataStoreHelper .cacheTimeSeconds
181197 val isCacheEnabled = DataStoreHelper .isCacheEnabled
198+ val diskKey = " ${api.name} _${page} _${nameIndex} "
182199
183200 if (isCacheEnabled) {
184201 val cached = homeCache.withLock {
@@ -193,6 +210,19 @@ class APIRepository(val api: MainAPI) {
193210 }
194211
195212 if (cached != null ) return Resource .Success (cached)
213+
214+ val cachedOnDisk = CloudStreamApp .getKey<SavedHomePageResponse >(HOME_CACHE_FOLDER , diskKey)
215+ if (cachedOnDisk != null && unixTime - cachedOnDisk.unixTime < cacheTtl) {
216+ homeCache.withLock {
217+ if (homeCache.size > HOME_CACHE_SIZE ) {
218+ homeCache[homeCacheIndex] = cachedOnDisk
219+ homeCacheIndex = (homeCacheIndex + 1 ) % HOME_CACHE_SIZE
220+ } else {
221+ homeCache.add(cachedOnDisk)
222+ }
223+ }
224+ return Resource .Success (cachedOnDisk.response)
225+ }
196226 }
197227
198228 return safeApiCall {
@@ -243,6 +273,7 @@ class APIRepository(val api: MainAPI) {
243273 homeCache.add(add)
244274 }
245275 }
276+ CloudStreamApp .setKey(HOME_CACHE_FOLDER , diskKey, add)
246277 }
247278
248279 res
0 commit comments