TorAddonCollectionProvider.kt 1.88 KB
Newer Older
Alex Catarineu's avatar
Alex Catarineu committed
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
53
54
55
56
57
58
59
60
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// Copyright (c) 2020, The Tor Project, Inc.

package org.mozilla.fenix.components

import android.content.Context
import android.graphics.Bitmap
import kotlinx.coroutines.withContext
import mozilla.components.concept.fetch.Client
import mozilla.components.feature.addons.Addon
import kotlinx.coroutines.Dispatchers
import mozilla.components.feature.addons.amo.AddonCollectionProvider
import java.io.IOException

internal const val COLLECTION_NAME = "tor_browser_collection"
internal const val ALLOWED_ADDONS_PATH = "allowed_addons.json"
internal const val MAX_CACHE_AGE = 1000L * 365L * 24L * 60L // 1000 years

class TorAddonCollectionProvider(
    private val context: Context,
    client: Client
) : AddonCollectionProvider(
    context, client, serverURL = "",
    collectionName = COLLECTION_NAME,
    maxCacheAgeInMinutes = MAX_CACHE_AGE
) {
    private var isCacheLoaded = false

    @Throws(IOException::class)
    override suspend fun getAvailableAddons(
        allowCache: Boolean,
        readTimeoutInSeconds: Long?
    ): List<Addon> {
        ensureCache()
        return super.getAvailableAddons(true, readTimeoutInSeconds)
    }

    @Throws(IOException::class)
    override suspend fun getAddonIconBitmap(addon: Addon): Bitmap? {
        ensureCache()
        return super.getAddonIconBitmap(addon)
    }

    @Throws(IOException::class)
    private suspend fun ensureCache() {
        if (isCacheLoaded) {
            return
        }
        return withContext(Dispatchers.IO) {
            val data = context.assets.open(ALLOWED_ADDONS_PATH).bufferedReader().use {
                it.readText()
            }
            writeToDiskCache(data)
            isCacheLoaded = true
        }
    }
}