APK反编译源代码展示 - 南明离火平台提供

应用版本信息
应用名称:Otteretto
版本号:3.3.1
包名称:com.chrisklimowski.otteretto

MD5 校验值:2295ee6ac84d61e12d0fa3df96db7b91

反编译源代码说明

PurchasePlugin.java 文件包含反编译后的源代码,请注意,该内容仅供学习和参考使用,不得用于非法用途。


package cc.fovea;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.PriceChangeConfirmationListener;
import com.android.billingclient.api.PriceChangeFlowParams;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PurchasePlugin extends CordovaPlugin implements PurchasesUpdatedListener, ConsumeResponseListener, AcknowledgePurchaseResponseListener {
    public static final int BILLING_CLIENT_NOT_CONNECTED = -1;
    private BillingClient mBillingClient;
    private CallbackContext mCallbackContext;
    private List<String> mInAppSkus;
    private boolean mIsServiceConnected;
    private List<String> mSubsSkus;
    private final String mTag = "CordovaPurchase";
    private final List<Purchase> mPurchases = new ArrayList();
    private BillingResult mBillingClientResult = BillingResult.newBuilder().setResponseCode(-1).build();
    private final HashMap<String, SkuDetails> mSkuDetails = new HashMap<>();
    private Set<String> mTokensToBeConsumed = new HashSet();
    private CallbackContext mListenerContext = null;
    private long mLastQueryOnStart = 0;
    private int nSkuDetailsQuerySuccessful = 0;

    private String codeToMessage(int i) {
        switch (i) {
            case -3:
                return "The request has reached the maximum timeout before Google Play responds";
            case -2:
                return "Requested feature is not supported by Play Store on the current device";
            case -1:
                return "Play Store service is not connected now - potentially transient state";
            case 0:
                return "Success";
            case 1:
                return "User pressed back or canceled a dialog";
            case 2:
                return "Network connection is down";
            case 3:
                return "Billing API version is not supported for the type requested";
            case 4:
                return "Requested product is not available for purchase";
            case 5:
                return "Invalid arguments provided to the API";
            case 6:
                return "Fatal error during the API action";
            case 7:
                return "Failure to purchase since item is already owned";
            case 8:
                return "Failure to consume since item is not owned";
            default:
                return "Unknown error code";
        }
    }

    public BillingResult getLastResult() {
        return this.mBillingClientResult;
    }

    private int getLastResponseCode() {
        return this.mBillingClientResult.getResponseCode();
    }

    private void resetLastResult(int i) {
        this.mBillingClientResult = BillingResult.newBuilder().setResponseCode(i).setDebugMessage("").build();
    }

    @Override
    public void initialize(CordovaInterface cordovaInterface, CordovaWebView cordovaWebView) {
        super.initialize(cordovaInterface, cordovaWebView);
    }

    public void sendToListener(String str, JSONObject jSONObject) {
        try {
            Log.d("CordovaPurchase", "sendToListener() -> " + str);
            Log.d("CordovaPurchase", "            data -> " + jSONObject.toString());
            if (this.mListenerContext == null) {
                return;
            }
            JSONObject put = new JSONObject().put("type", str);
            if (jSONObject != null) {
                put.put("data", jSONObject);
            }
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, put);
            pluginResult.setKeepCallback(true);
            this.mListenerContext.sendPluginResult(pluginResult);
        } catch (JSONException e) {
            Log.d("CordovaPurchase", "sendToListener() -> Failed: " + e.getMessage());
        }
    }

    @Override
    public boolean execute(String str, JSONArray jSONArray, CallbackContext callbackContext) {
        if ("setListener".equals(str)) {
            this.mListenerContext = callbackContext;
            sendToListener("ready", new JSONObject());
            return true;
        }
        this.mCallbackContext = callbackContext;
        Boolean bool = true;
        try {
            if ("init".equals(str)) {
                init(parseStringArrayAtIndex(jSONArray, 1), parseStringArrayAtIndex(jSONArray, 2));
            } else if ("getAvailableProducts".equals(str)) {
                getAvailableProducts();
            } else if ("getPurchases".equals(str)) {
                getPurchases();
            } else if ("consumePurchase".equals(str)) {
                consumePurchase(jSONArray.getString(0));
            } else if ("acknowledgePurchase".equals(str)) {
                acknowledgePurchase(jSONArray.getString(0));
            } else if ("buy".equals(str)) {
                buy(jSONArray);
            } else if ("subscribe".equals(str)) {
                subscribe(jSONArray);
            } else if ("manageSubscriptions".equals(str)) {
                this.cordova.getActivity().startActivity(new Intent("android.intent.action.VIEW", Uri.parse("http://play.google.com/store/account/subscriptions")));
            } else if ("manageBilling".equals(str)) {
                this.cordova.getActivity().startActivity(new Intent("android.intent.action.VIEW", Uri.parse("http://play.google.com/store/paymentmethods")));
            } else if ("launchPriceChangeConfirmationFlow".equals(str)) {
                launchPriceChangeConfirmationFlow(jSONArray.getString(0));
            } else {
                bool = false;
            }
        } catch (IllegalStateException e) {
            callError(Constants.ERR_UNKNOWN, e.getMessage());
        } catch (JSONException e2) {
            callError(Constants.ERR_UNKNOWN, e2.getMessage());
        }
        return bool.booleanValue();
    }

    private String getPublicKey() {
        int identifier = this.cordova.getActivity().getResources().getIdentifier("billing_key_param", "string", this.cordova.getActivity().getPackageName());
        if (identifier > 0) {
            String string = this.cordova.getActivity().getString(identifier);
            if (string.length() > 0) {
                return string;
            }
        }
        return this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("billing_key", "string", this.cordova.getActivity().getPackageName()));
    }

    private void init(List<String> list, List<String> list2) {
        Log.d("CordovaPurchase", "init()");
        this.mInAppSkus = list;
        this.mSubsSkus = list2;
        this.mBillingClient = BillingClient.newBuilder(this.cordova.getActivity()).enablePendingPurchases().setListener(this).build();
        resetLastResult(-1);
        startServiceConnection(new Runnable() {
            @Override
            public final void run() {
                PurchasePlugin.this.m54lambda$init$0$ccfoveaPurchasePlugin();
            }
        });
    }

    public void m54lambda$init$0$ccfoveaPurchasePlugin() {
        if (getLastResponseCode() == 0) {
            Log.d("CordovaPurchase", "init() -> Success");
            callSuccess();
            return;
        }
        Log.d("CordovaPurchase", "init() -> Failed: " + format(getLastResult()));
        callError(Constants.ERR_SETUP, "Setup failed. " + format(getLastResult()));
    }

    private void getPurchases() {
        Log.d("CordovaPurchase", "getPurchases()");
        queryPurchases();
    }

    private void onQueryPurchasesFinished(Purchase.PurchasesResult purchasesResult) {
        try {
            if (purchasesResult.getResponseCode() == 0) {
                Iterator<Purchase> it = purchasesResult.getPurchasesList().iterator();
                while (it.hasNext()) {
                    this.mPurchases.add(0, it.next());
                }
                sendToListener("setPurchases", new JSONObject().put("purchases", toJSON(purchasesResult.getPurchasesList())));
                callSuccess(toJSON(purchasesResult.getPurchasesList()));
                return;
            }
            callError(Constants.ERR_LOAD, "Failed to query purchases: " + purchasesResult.getResponseCode());
        } catch (Exception e) {
            Log.e("CordovaPurchase", "onQueryPurchasesFinished() -> Failed: " + e.getMessage());
            callError(Constants.ERR_LOAD, "Failed to query purchases: " + e.getMessage());
        }
    }

    private JSONArray toJSON(List<Purchase> list) throws JSONException {
        JSONArray jSONArray = new JSONArray();
        Iterator<Purchase> it = list.iterator();
        while (it.hasNext()) {
            jSONArray.put(toJSON(it.next()));
        }
        return jSONArray;
    }

    private JSONObject toJSON(Purchase purchase) throws JSONException {
        return new JSONObject(purchase.getOriginalJson()).put("orderId", purchase.getOrderId()).put("getPurchaseState", purchase.getPurchaseState()).put("acknowledged", purchase.isAcknowledged()).put("autoRenewing", purchase.isAutoRenewing()).put("signature", purchase.getSignature()).put("receipt", purchase.getOriginalJson().toString());
    }

    public void queryPurchases() {
        Log.d("CordovaPurchase", "queryPurchases()");
        executeServiceRequest(new Runnable() {
            @Override
            public final void run() {
                PurchasePlugin.this.m56lambda$queryPurchases$1$ccfoveaPurchasePlugin();
            }
        });
    }

    public void m56lambda$queryPurchases$1$ccfoveaPurchasePlugin() {
        long currentTimeMillis = System.currentTimeMillis();
        Purchase.PurchasesResult queryPurchases = this.mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
        ArrayList arrayList = new ArrayList();
        BillingResult billingResult = queryPurchases.getBillingResult();
        if (billingResult.getResponseCode() == 0) {
            arrayList.addAll(queryPurchases.getPurchasesList());
        }
        Log.i("CordovaPurchase", "queryPurchases() -> Elapsed time: " + (System.currentTimeMillis() - currentTimeMillis) + "ms");
        if (areSubscriptionsSupported()) {
            Purchase.PurchasesResult queryPurchases2 = this.mBillingClient.queryPurchases(BillingClient.SkuType.SUBS);
            Log.i("CordovaPurchase", "queryPurchases() -> Subscriptions elapsed time: " + (System.currentTimeMillis() - currentTimeMillis) + "ms");
            Log.i("CordovaPurchase", "queryPurchases() -> Subscriptions result code: " + queryPurchases2.getResponseCode() + " res: " + (queryPurchases2.getPurchasesList() != null ? queryPurchases2.getPurchasesList().size() : -1));
            if (queryPurchases2.getResponseCode() == 0 && queryPurchases2.getPurchasesList() != null) {
                BillingResult billingResult2 = queryPurchases2.getBillingResult();
                arrayList.addAll(queryPurchases2.getPurchasesList());
                billingResult = billingResult2;
            } else {
                Log.e("CordovaPurchase", "queryPurchases() -> Error trying to query subscription purchases.");
            }
        } else if (queryPurchases.getResponseCode() == 0) {
            Log.i("CordovaPurchase", "queryPurchases() -> Subscriptions are not supported, skipped.");
        } else {
            Log.w("CordovaPurchase", "queryPurchases() -> Error response code: " + queryPurchases.getResponseCode());
        }
        onQueryPurchasesFinished(new Purchase.PurchasesResult(billingResult, arrayList));
    }

    public boolean areSubscriptionsSupported() {
        BillingResult isFeatureSupported = this.mBillingClient.isFeatureSupported(BillingClient.FeatureType.SUBSCRIPTIONS);
        if (isFeatureSupported.getResponseCode() == 0) {
            return true;
        }
        Log.w("CordovaPurchase", "areSubscriptionsSupported() -> Failed: " + format(isFeatureSupported));
        return false;
    }

    private void getAvailableProducts() {
        Log.d("CordovaPurchase", "getAvailableProducts()");
        queryAllSkuDetails(new SkuDetailsResponseListener() {
            @Override
            public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> list) {
                if (billingResult.getResponseCode() != 0) {
                    Log.d("CordovaPurchase", "getAvailableProducts() -> Failed: " + PurchasePlugin.this.format(billingResult));
                    PurchasePlugin.this.callError(Constants.ERR_LOAD, "Failed to load SKUs, code: " + billingResult.getResponseCode());
                    return;
                }
                JSONArray jSONArray = new JSONArray();
                try {
                    Iterator<SkuDetails> it = list.iterator();
                    while (it.hasNext()) {
                        jSONArray.put(new JSONObject(it.next().getOriginalJson()));
                    }
                    Log.d("CordovaPurchase", "getAvailableProducts() -> Success");
                    PurchasePlugin.this.callSuccess(jSONArray);
                } catch (JSONException e) {
                    Log.d("CordovaPurchase", "getAvailableProducts() -> Failed: " + e.getMessage());
                    PurchasePlugin.this.callError(Constants.ERR_LOAD, e.getMessage());
                }
            }
        });
    }

    private Purchase findPurchaseByToken(String str) {
        for (Purchase purchase : this.mPurchases) {
            if (purchase.getPurchaseToken().equals(str)) {
                return purchase;
            }
        }
        return null;
    }

    private Purchase findPurchaseBySku(String str) {
        for (Purchase purchase : this.mPurchases) {
            if (purchase.getSkus().contains(str)) {
                return purchase;
            }
        }
        return null;
    }

    @Override
    public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> list) {
        try {
            int responseCode = billingResult.getResponseCode();
            if (responseCode == 0) {
                Log.d("CordovaPurchase", "onPurchasesUpdated() -> Success");
                Iterator<Purchase> it = list.iterator();
                while (it.hasNext()) {
                    this.mPurchases.add(0, it.next());
                }
                callSuccess();
                sendToListener("purchasesUpdated", new JSONObject().put("purchases", toJSON(list)));
                return;
            }
            if (responseCode == 1) {
                Log.w("CordovaPurchase", "onPurchasesUpdated() -> Cancelled: " + format(billingResult));
                callError(Constants.ERR_CANCELLED, codeToString(responseCode));
                return;
            }
            Log.w("CordovaPurchase", "onPurchasesUpdated() -> Failed: " + format(billingResult));
            callError(Constants.ERR_PURCHASE, codeToString(responseCode));
        } catch (JSONException e) {
            Log.w("CordovaPurchase", "onPurchasesUpdated() -> JSONException " + e.getMessage());
            callError(Constants.ERR_PURCHASE, e.getMessage());
        }
    }

    private String codeToString(int i) {
        switch (i) {
            case -3:
                return "SERVICE_TIMEOUT";
            case -2:
                return "FEATURE_NOT_SUPPORTED";
            case -1:
                return "SERVICE_DISCONNECTED";
            case 0:
                return "OK";
            case 1:
                return "USER_CANCELED";
            case 2:
                return "SERVICE_UNAVAILABLE";
            case 3:
                return "BILLING_UNAVAILABLE";
            case 4:
                return "ITEM_UNAVAILABLE";
            case 5:
                return "DEVELOPER_ERROR";
            case 6:
                return "ERROR";
            case 7:
                return "ITEM_ALREADY_OWNED";
            case 8:
                return "ITEM_NOT_OWNED";
            default:
                return "CODE_" + i;
        }
    }

    private BillingFlowParams parseBillingFlowParams(JSONArray jSONArray) throws JSONException {
        String string = jSONArray.getString(0);
        JSONObject jSONObject = jSONArray.getJSONObject(1);
        String string2 = jSONObject.has("oldPurchaseToken") ? jSONObject.getString("oldPurchaseToken") : null;
        String string3 = jSONObject.has(BillingFlowParams.EXTRA_PARAM_KEY_ACCOUNT_ID) ? jSONObject.getString(BillingFlowParams.EXTRA_PARAM_KEY_ACCOUNT_ID) : null;
        String string4 = jSONObject.has("profileId") ? jSONObject.getString("profileId") : null;
        BillingFlowParams.Builder newBuilder = BillingFlowParams.newBuilder();
        BillingFlowParams.SubscriptionUpdateParams.Builder newBuilder2 = BillingFlowParams.SubscriptionUpdateParams.newBuilder();
        Boolean bool = false;
        SkuDetails skuDetails = this.mSkuDetails.get(string);
        if (skuDetails == null) {
            Log.d("CordovaPurchase", "buy() -> Failed: Product not registered: " + string);
            callError(Constants.ERR_PURCHASE, "Product not registered: " + string);
            return null;
        }
        Log.d("CordovaPurchase", "buy() -> setSkuDetails");
        newBuilder.setSkuDetails(skuDetails);
        if (string2 != null) {
            Log.d("CordovaPurchase", "buy() -> setOldSkuPurchaseToken");
            newBuilder2.setOldSkuPurchaseToken(string2);
            bool = true;
        }
        if (string3 != null) {
            Log.d("CordovaPurchase", "buy() -> setObfuscatedAccountId");
            newBuilder.setObfuscatedAccountId(string3);
        }
        if (string4 != null) {
            Log.d("CordovaPurchase", "buy() -> setObfuscatedProfileId");
            newBuilder.setObfuscatedProfileId(string4);
        }
        String string5 = jSONObject.has(BillingFlowParams.EXTRA_PARAM_KEY_REPLACE_SKUS_PRORATION_MODE) ? jSONObject.getString(BillingFlowParams.EXTRA_PARAM_KEY_REPLACE_SKUS_PRORATION_MODE) : null;
        if (string5 != null) {
            if ("IMMEDIATE_WITH_TIME_PRORATION".equals(string5)) {
                newBuilder2.setReplaceSkusProrationMode(1);
            } else if ("IMMEDIATE_AND_CHARGE_PRORATED_PRICE".equals(string5)) {
                newBuilder2.setReplaceSkusProrationMode(2);
            } else if ("IMMEDIATE_WITHOUT_PRORATION".equals(string5)) {
                newBuilder2.setReplaceSkusProrationMode(3);
            } else if ("DEFERRED".equals(string5)) {
                newBuilder2.setReplaceSkusProrationMode(4);
            } else if ("IMMEDIATE_AND_CHARGE_FULL_PRICE".equals(string5)) {
                newBuilder2.setReplaceSkusProrationMode(5);
            }
        }
        if (bool.booleanValue()) {
            newBuilder.setSubscriptionUpdateParams(newBuilder2.build());
        }
        return newBuilder.build();
    }

    private void subscribe(JSONArray jSONArray) throws JSONException {
        Log.d("CordovaPurchase", "subscribe()");
        if (!areSubscriptionsSupported()) {
            callError(Constants.ERR_PURCHASE, "FEATURE_NOT_SUPPORTED");
        } else {
            initiatePurchaseFlow(parseBillingFlowParams(jSONArray));
        }
    }

    private void buy(JSONArray jSONArray) throws JSONException {
        Log.d("CordovaPurchase", "buy()");
        initiatePurchaseFlow(parseBillingFlowParams(jSONArray));
    }

    public void initiatePurchaseFlow(final BillingFlowParams billingFlowParams) {
        Log.d("CordovaPurchase", "initiatePurchaseFlow()");
        if (billingFlowParams == null) {
            return;
        }
        executeServiceRequest(new Runnable() {
            @Override
            public final void run() {
                PurchasePlugin.this.m55lambda$initiatePurchaseFlow$2$ccfoveaPurchasePlugin(billingFlowParams);
            }
        });
    }

    public void m55lambda$initiatePurchaseFlow$2$ccfoveaPurchasePlugin(BillingFlowParams billingFlowParams) {
        if (getLastResponseCode() != 0) {
            Log.d("CordovaPurchase", "initiatePurchaseFlow() -> Failed: Failed to execute service request. " + format(getLastResult()));
            callError(Constants.ERR_COMMUNICATION, "Failed to execute service request. " + format(getLastResult()));
            return;
        }
        Log.d("CordovaPurchase", "initiatePurchaseFlow() -> launchBillingFlow.");
        this.cordova.setActivityResultCallback(this);
        this.mBillingClient.launchBillingFlow(this.cordova.getActivity(), billingFlowParams);
    }

    @Override
    public void onActivityResult(int i, int i2, Intent intent) {
        try {
            Log.d("CordovaPurchase", "onActivityResult(" + i + "," + i2 + "," + intent + ")");
            Log.d("CordovaPurchase", "onActivityResult() -> super.onActivityResult()");
            super.onActivityResult(i, i2, intent);
        } catch (Exception e) {
            Log.e("CordovaPurchase", "onActivityResult() -> Failed: " + e.getMessage());
            callError(Constants.ERR_UNKNOWN, e.getMessage());
        }
    }

    private void consumePurchase(String str) throws JSONException {
        Log.d("CordovaPurchase", "consumePurchase(" + str + ")");
        Purchase findPurchaseBySku = findPurchaseBySku(str);
        if (findPurchaseBySku == null) {
            Log.w("CordovaPurchase", "consumePurchase() -> No such purchase");
            callError(Constants.ERR_PURCHASE, "ITEM_NOT_OWNED");
            return;
        }
        final String purchaseToken = findPurchaseBySku.getPurchaseToken();
        if (this.mTokensToBeConsumed.contains(purchaseToken)) {
            Log.i("CordovaPurchase", "consumePurchase() -> Consume already in progress.");
            callError(Constants.ERR_PURCHASE, "ITEM_ALREADY_CONSUMED");
        } else {
            this.mTokensToBeConsumed.add(purchaseToken);
            executeServiceRequest(new Runnable() {
                @Override
                public final void run() {
                    PurchasePlugin.this.m53lambda$consumePurchase$3$ccfoveaPurchasePlugin(purchaseToken);
                }
            });
        }
    }

    public void m53lambda$consumePurchase$3$ccfoveaPurchasePlugin(String str) {
        this.mBillingClient.consumeAsync(ConsumeParams.newBuilder().setPurchaseToken(str).build(), this);
    }

    private void acknowledgePurchase(String str) throws JSONException {
        Log.d("CordovaPurchase", "acknowledgePurchase(" + str + ")");
        Purchase findPurchaseBySku = findPurchaseBySku(str);
        if (findPurchaseBySku == null) {
            Log.w("CordovaPurchase", "acknowledgePurchase() -> No such purchase");
            callError(Constants.ERR_PURCHASE, "ITEM_NOT_OWNED");
        } else {
            final String purchaseToken = findPurchaseBySku.getPurchaseToken();
            executeServiceRequest(new Runnable() {
                @Override
                public final void run() {
                    PurchasePlugin.this.m52lambda$acknowledgePurchase$4$ccfoveaPurchasePlugin(purchaseToken);
                }
            });
        }
    }

    public void m52lambda$acknowledgePurchase$4$ccfoveaPurchasePlugin(String str) {
        this.mBillingClient.acknowledgePurchase(AcknowledgePurchaseParams.newBuilder().setPurchaseToken(str).build(), this);
    }

    @Override
    public void onAcknowledgePurchaseResponse(BillingResult billingResult) {
        if (billingResult.getResponseCode() == 0) {
            Log.d("CordovaPurchase", "onAcknowledgePurchaseResponse() -> Success");
            callSuccess();
            return;
        }
        Log.d("CordovaPurchase", "onAcknowledgePurchaseResponse() -> Failed: " + format(billingResult));
        callError(Constants.ERR_FINISH, format(billingResult));
    }

    public void launchPriceChangeConfirmationFlow(String str) {
        Log.d("CordovaPurchase", "launchPriceChangeConfirmationFlow(" + str + ")");
        SkuDetails skuDetails = this.mSkuDetails.get(str);
        if (skuDetails == null) {
            Log.d("CordovaPurchase", "launchPriceChangeConfirmationFlow() -> Failed: Product not registered: " + str);
            sendToListener("onPriceChangeConfirmationResultUnknownSku", new JSONObject());
            return;
        }
        this.mBillingClient.launchPriceChangeConfirmationFlow(this.cordova.getActivity(), PriceChangeFlowParams.newBuilder().setSkuDetails(skuDetails).build(), new PriceChangeConfirmationListener() {
            @Override
            public void onPriceChangeConfirmationResult(BillingResult billingResult) {
                int responseCode = billingResult.getResponseCode();
                if (responseCode == 0) {
                    PurchasePlugin.this.sendToListener("onPriceChangeConfirmationResultOK", new JSONObject());
                } else if (responseCode == 1) {
                    PurchasePlugin.this.sendToListener("onPriceChangeConfirmationResultUserCanceled", new JSONObject());
                }
            }
        });
    }

    @Override
    public void onNewIntent(Intent intent) {
        Log.d("CordovaPurchase", "onNewIntent()");
    }

    @Override
    public void onStop() {
        Log.d("CordovaPurchase", "onStop()");
    }

    @Override
    public void onStart() {
        Log.d("CordovaPurchase", "onStart()");
        if (this.mBillingClient == null || Calendar.getInstance().getTimeInMillis() - this.mLastQueryOnStart <= 86400000) {
            return;
        }
        this.mLastQueryOnStart = Calendar.getInstance().getTimeInMillis();
        queryPurchases();
    }

    @Override
    public void onConsumeResponse(BillingResult billingResult, String str) {
        try {
            Log.d("CordovaPurchase", "onConsumeResponse()");
            if (billingResult.getResponseCode() == 0) {
                this.mTokensToBeConsumed.remove(str);
                Purchase findPurchaseByToken = findPurchaseByToken(str);
                Log.d("CordovaPurchase", "onConsumeResponse() -> Success");
                sendToListener("purchaseConsumed", new JSONObject().put("purchase", toJSON(findPurchaseByToken)));
            }
        } catch (JSONException e) {
            Log.d("CordovaPurchase", "onConsumeResponse() -> Failed: " + e.getMessage());
        }
    }

    @Override
    public void onDestroy() {
        BillingClient billingClient = this.mBillingClient;
        if (billingClient != null && billingClient.isReady()) {
            this.mBillingClient.endConnection();
        }
        super.onDestroy();
    }

    private void queryAllSkuDetails(final SkuDetailsResponseListener skuDetailsResponseListener) {
        Log.d("CordovaPurchase", "queryAllSkuDetails()");
        final ArrayList arrayList = new ArrayList();
        final int i = (this.mSubsSkus.size() > 0 ? 1 : 0) + (this.mInAppSkus.size() <= 0 ? 0 : 1);
        this.nSkuDetailsQuerySuccessful = 0;
        SkuDetailsResponseListener skuDetailsResponseListener2 = new SkuDetailsResponseListener() {
            @Override
            public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> list) {
                PurchasePlugin.this.mBillingClientResult = billingResult;
                if (billingResult.getResponseCode() != 0) {
                    Log.w("CordovaPurchase", "queryAllSkuDetails() -> Failed: Unsuccessful query. " + PurchasePlugin.this.format(billingResult));
                    PurchasePlugin.this.callError(Constants.ERR_LOAD, "Error. " + PurchasePlugin.this.format(billingResult));
                    return;
                }
                if (list != null && list.size() > 0) {
                    for (SkuDetails skuDetails : list) {
                        Log.d("CordovaPurchase", "queryAllSkuDetails() -> SKUDetails: Title: " + skuDetails.getTitle());
                        PurchasePlugin.this.mSkuDetails.put(skuDetails.getSku(), skuDetails);
                        arrayList.add(skuDetails);
                    }
                } else {
                    Log.w("CordovaPurchase", "queryAllSkuDetails() -> Query returned nothing.");
                }
                PurchasePlugin.this.nSkuDetailsQuerySuccessful++;
                if (PurchasePlugin.this.nSkuDetailsQuerySuccessful != i || skuDetailsResponseListener == null) {
                    return;
                }
                Log.d("CordovaPurchase", "queryAllSkuDetails() -> Calling listener.");
                skuDetailsResponseListener.onSkuDetailsResponse(billingResult, arrayList);
            }
        };
        if (this.mInAppSkus.size() > 0) {
            Log.d("CordovaPurchase", "queryAllSkuDetails() -> Query INAPP.");
            querySkuDetailsAsync(BillingClient.SkuType.INAPP, this.mInAppSkus, skuDetailsResponseListener2);
        }
        if (this.mSubsSkus.size() > 0) {
            Log.d("CordovaPurchase", "queryAllSkuDetails() -> Query SUBS.");
            querySkuDetailsAsync(BillingClient.SkuType.SUBS, this.mSubsSkus, skuDetailsResponseListener2);
        }
        if (i != 0 || skuDetailsResponseListener == null) {
            return;
        }
        Log.d("CordovaPurchase", "queryAllSkuDetails() -> Calling listener (0 requests).");
        skuDetailsResponseListener.onSkuDetailsResponse(getLastResult(), arrayList);
    }

    public void querySkuDetailsAsync(final String str, final List<String> list, final SkuDetailsResponseListener skuDetailsResponseListener) {
        Log.d("CordovaPurchase", "querySkuDetailsAsync()");
        executeServiceRequest(new Runnable() {
            @Override
            public final void run() {
                PurchasePlugin.this.m57lambda$querySkuDetailsAsync$5$ccfoveaPurchasePlugin(skuDetailsResponseListener, list, str);
            }
        });
    }

    public void m57lambda$querySkuDetailsAsync$5$ccfoveaPurchasePlugin(SkuDetailsResponseListener skuDetailsResponseListener, List list, String str) {
        if (getLastResponseCode() != 0) {
            Log.d("CordovaPurchase", "querySkuDetailsAsync() -> Failed: " + format(getLastResult()));
            skuDetailsResponseListener.onSkuDetailsResponse(getLastResult(), null);
            return;
        }
        Log.d("CordovaPurchase", "querySkuDetailsAsync() -> Success");
        SkuDetailsParams.Builder newBuilder = SkuDetailsParams.newBuilder();
        newBuilder.setSkusList(list).setType(str);
        this.mBillingClient.querySkuDetailsAsync(newBuilder.build(), skuDetailsResponseListener);
    }

    private void callSuccess() {
        CallbackContext callbackContext = this.mCallbackContext;
        if (callbackContext == null) {
            return;
        }
        this.mCallbackContext = null;
        callbackContext.success();
    }

    public void callSuccess(JSONArray jSONArray) {
        CallbackContext callbackContext = this.mCallbackContext;
        if (callbackContext == null) {
            return;
        }
        this.mCallbackContext = null;
        callbackContext.success(jSONArray);
    }

    public void callError(int i, String str) {
        Log.d("CordovaPurchase", "callError({code:" + i + ", msg:\"" + str + "\")");
        CallbackContext callbackContext = this.mCallbackContext;
        if (callbackContext == null) {
            return;
        }
        this.mCallbackContext = null;
        callbackContext.error(i + "|" + str);
    }

    public void startServiceConnection(final Runnable runnable) {
        Log.d("CordovaPurchase", "startServiceConnection()");
        this.mBillingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(BillingResult billingResult) {
                PurchasePlugin.this.mBillingClientResult = billingResult;
                if (billingResult.getResponseCode() == 0) {
                    Log.d("CordovaPurchase", "startServiceConnection() -> Success");
                    PurchasePlugin.this.mIsServiceConnected = true;
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append("startServiceConnection() -> Failed: ");
                    PurchasePlugin purchasePlugin = PurchasePlugin.this;
                    sb.append(purchasePlugin.format(purchasePlugin.getLastResult()));
                    Log.d("CordovaPurchase", sb.toString());
                }
                Runnable runnable2 = runnable;
                if (runnable2 != null) {
                    runnable2.run();
                }
            }

            @Override
            public void onBillingServiceDisconnected() {
                Log.d("CordovaPurchase", "startServiceConnection() -> Disconnected");
                PurchasePlugin.this.mIsServiceConnected = false;
            }
        });
    }

    private void executeServiceRequest(Runnable runnable) {
        if (this.mIsServiceConnected) {
            Log.d("CordovaPurchase", "executeServiceRequest() -> OK");
            resetLastResult(0);
            runnable.run();
        } else {
            Log.d("CordovaPurchase", "executeServiceRequest() -> Failed (try again).");
            startServiceConnection(runnable);
        }
    }

    private List<String> parseStringArrayAtIndex(JSONArray jSONArray, int i) throws JSONException {
        ArrayList arrayList = new ArrayList();
        if (jSONArray.length() > i) {
            JSONArray jSONArray2 = new JSONArray(jSONArray.getString(i));
            int length = jSONArray2.length();
            for (int i2 = 0; i2 < length; i2++) {
                arrayList.add(jSONArray2.get(i2).toString());
            }
        }
        return arrayList;
    }

    public String format(BillingResult billingResult) {
        String codeToMessage;
        int responseCode = billingResult.getResponseCode();
        if (billingResult.getDebugMessage() != "") {
            codeToMessage = billingResult.getDebugMessage();
        } else {
            codeToMessage = codeToMessage(responseCode);
        }
        return codeToString(responseCode) + ": " + codeToMessage;
    }
}