aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/utils/iab/IABBinder.kt
blob: 7f6e8a6db28b30ae49f03d5b1c44bdc1645466be (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package com.pitchedapps.frost.utils.iab

import android.app.Activity
import android.content.Intent
import com.anjlab.android.iab.v3.BillingProcessor
import com.anjlab.android.iab.v3.TransactionDetails
import com.crashlytics.android.answers.PurchaseEvent
import com.pitchedapps.frost.BuildConfig
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.Prefs
import com.pitchedapps.frost.utils.frostAnswers
import com.pitchedapps.frost.utils.logFrostAnswers
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.onComplete
import org.jetbrains.anko.uiThread
import java.lang.ref.WeakReference
import java.math.BigDecimal
import java.util.*

/**
 * Created by Allan Wang on 2017-07-22.
 */
private const val FROST_PRO = "frost_pro"

/**
 * Implemented pro checker with a hook for debug builds
 * Use this when checking if the pro feature is enabled
 */
val IS_FROST_PRO: Boolean
    get() = (BuildConfig.DEBUG && Prefs.debugPro) || Prefs.pro

interface FrostBilling : BillingProcessor.IBillingHandler {
    fun Activity.onCreateBilling()
    fun onDestroyBilling()
    fun purchasePro()
    fun restorePurchases()
    fun onActivityResultBilling(requestCode: Int, resultCode: Int, data: Intent?): Boolean
}

abstract class IABBinder : FrostBilling {

    var bp: BillingProcessor? = null
    lateinit var activityRef: WeakReference<Activity>
    val activity
        get() = activityRef.get()

    override final fun Activity.onCreateBilling() {
        activityRef = WeakReference(this)
        doAsync {
            bp = BillingProcessor.newBillingProcessor(this@onCreateBilling, PUBLIC_BILLING_KEY, this@IABBinder)
            bp?.initialize()
        }
    }

    override fun onDestroyBilling() {
        activityRef.clear()
        bp?.release()
        bp = null
    }

    override fun onBillingInitialized() = L.i("IAB initialized")

    override fun onPurchaseHistoryRestored() = L.d("IAB restored")

    override fun onProductPurchased(productId: String, details: TransactionDetails?) {
        bp.doAsync {
            L.i("IAB $productId purchased")
            val listing = weakRef.get()?.getPurchaseListingDetails(productId) ?: return@doAsync
            val currency = try {
                Currency.getInstance(listing.currency)
            } catch (e: Exception) {
                null
            }
            frostAnswers {
                logPurchase(PurchaseEvent().apply {
                    putItemId(productId)
                    putSuccess(true)
                    if (currency != null) {
                        putCurrency(Currency.getInstance(Locale.getDefault()))
                        putItemType(productId)
                        putItemPrice(BigDecimal.valueOf(listing.priceValue))
                    }
                })
            }
        }
    }

    override fun onBillingError(errorCode: Int, error: Throwable?) {
        frostAnswers {
            logPurchase(PurchaseEvent()
                    .putCustomAttribute("result", errorCode.toString())
                    .putSuccess(false))
        }
        error.logFrostAnswers("IAB error $errorCode")
    }

    override fun onActivityResultBilling(requestCode: Int, resultCode: Int, data: Intent?): Boolean
            = bp?.handleActivityResult(requestCode, resultCode, data) ?: false

    override fun purchasePro() {
        val bp = this.bp
        if (bp == null) {
            frostAnswers {
                logPurchase(PurchaseEvent()
                        .putCustomAttribute("result", "null bp")
                        .putSuccess(false))
            }
            L.eThrow("IAB null bp on purchase attempt")
            return
        }
        val a = activity ?: return

        if (!BillingProcessor.isIabServiceAvailable(a) || !bp.isOneTimePurchaseSupported)
            a.playStorePurchaseUnsupported()
        else
            bp.purchase(a, FROST_PRO)
    }

}

class IABSettings : IABBinder() {

    override fun onProductPurchased(productId: String, details: TransactionDetails?) {
        super.onProductPurchased(productId, details)
        activity?.playStorePurchasedSuccessfully(productId)
    }

    override fun onBillingError(errorCode: Int, error: Throwable?) {
        super.onBillingError(errorCode, error)
        activity?.playStoreGenericError(null)
    }

    /**
     * Attempts to get pro, or launch purchase flow if user doesn't have it
     */
    override fun restorePurchases() {
        bp.doAsync {
            val load = weakRef.get()?.loadOwnedPurchasesFromGoogle() ?: return@doAsync
            L.d("IAB settings load from google $load")
            uiThread {
                if (!(weakRef.get()?.isPurchased(FROST_PRO) ?: return@uiThread)) {
                    if (Prefs.pro) activity.playStoreNoLongerPro()
                    else purchasePro()
                } else {
                    if (!Prefs.pro) activity.playStoreFoundPro()
                    else activity?.purchaseRestored()
                }
            }
        }
    }
}

class IABMain : IABBinder() {

    override fun onBillingInitialized() {
        super.onBillingInitialized()
        restorePurchases()
    }

    override fun onPurchaseHistoryRestored() {
        super.onPurchaseHistoryRestored()
        restorePurchases()
    }

    private var restored = false

    /**
     * Checks for pro and only does so once
     * A null check is added but it should never happen
     * given that this is only called with bp is ready
     */
    override fun restorePurchases() {
        if (restored || bp == null) return
        restored = true
        bp.doAsync {
            val load = weakRef.get()?.loadOwnedPurchasesFromGoogle() ?: false
            L.d("IAB main load from google $load")
            onComplete {
                if (!(weakRef.get()?.isPurchased(FROST_PRO) ?: false)) {
                    if (Prefs.pro) activity.playStoreNoLongerPro()
                } else {
                    if (!Prefs.pro) activity.playStoreFoundPro()
                }
                onDestroyBilling()
            }
        }
    }
}