package com.urbanairship.iap;

import android.content.SharedPreferences;
import android.os.Environment;
import com.urbanairship.Logger;
import com.urbanairship.UAirship;
import com.urbanairship.iap.Inventory;
import com.urbanairship.iap.Product;
import com.urbanairship.iap.PurchaseNotificationInfo;
import com.urbanairship.restclient.AppAuthenticatedRequest;
import com.urbanairship.restclient.AsyncHandler;
import com.urbanairship.restclient.Request;
import com.urbanairship.restclient.RequestQueue;
import com.urbanairship.restclient.Response;
import com.urbanairship.util.UnzipperTask;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.json.JSONObject;
import org.json.JSONTokener;

/* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
public class DownloadManager {
    static final int MAX_TRIES = 3;
    static final String PENDING_PRODUCTS_FILE = "com.urbanairship.iap.pending_products";
    private InventoryObserver inventoryObserver = new InventoryObserver();
    private HashMap<String, Integer> tries = new HashMap<>();
    private RequestQueue queue = new RequestQueue();
    private NotificationController notificationController = new NotificationController();

    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    private class InventoryObserver implements Observer {
        private InventoryObserver() {
        }

        @Override // java.util.Observer
        public void update(Observable observable, Object obj) {
            if (((Inventory) obj).getStatus() == Inventory.Status.LOADED) {
                if (IAPManager.isFirstRun() && IAPManager.isBillingSupported()) {
                    IAPManager.shared().restoreTransactions();
                } else {
                    DownloadManager.this.resumePendingProducts();
                }
            }
        }
    }

    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
    private class UnzipDelegate extends UnzipperTask.Delegate {
        File downloadPath;
        Product product;

        public UnzipDelegate(Product product, File file) {
            this.product = product;
            this.downloadPath = file;
        }

        @Override // com.urbanairship.util.UnzipperTask.Delegate
        public void onFail(Exception exc) {
            String identifier = this.product.getIdentifier();
            Logger.error(String.format("Extraction of %s failed", this.product.getTitle()), exc);
            PurchaseNotificationInfo purchaseNotificationInfo = DownloadManager.this.notificationController.get(identifier);
            purchaseNotificationInfo.setNotificationType(PurchaseNotificationInfo.NotificationType.DECOMPRESS_FAILED);
            DownloadManager.this.notificationController.sendNotification(purchaseNotificationInfo);
            DownloadManager.this.retry(this.product);
        }

        @Override // com.urbanairship.util.UnzipperTask.Delegate
        public void onProgressUpdate(int i) {
        }

        @Override // com.urbanairship.util.UnzipperTask.Delegate
        public void onSuccess() {
            String identifier = this.product.getIdentifier();
            PurchaseNotificationInfo purchaseNotificationInfo = DownloadManager.this.notificationController.get(identifier);
            purchaseNotificationInfo.setNotificationType(PurchaseNotificationInfo.NotificationType.INSTALL_SUCCESSFUL);
            this.product.setStatus(Product.Status.INSTALLED);
            this.product.setDownloadPath(this.downloadPath);
            Logger.verbose("Setting download path for " + purchaseNotificationInfo.getProductName() + ": " + this.downloadPath);
            Receipt fetch = Receipt.fetch(this.product.getIdentifier());
            fetch.setDownloadPathString(this.downloadPath.toString());
            fetch.serialize();
            DownloadManager.this.notificationController.removePurchaseNotification(identifier);
            DownloadManager.this.removePendingProduct(identifier);
            DownloadManager.this.tries.remove(identifier);
            IAPEventListener eventListener = IAPManager.shared().getEventListener();
            if (eventListener != null) {
                eventListener.downloadSuccessful(this.product);
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public DownloadManager() {
        IAPManager.shared().getInventory().addObserver(this.inventoryObserver);
    }

    private void addPendingProduct(String str) {
        SharedPreferences.Editor edit = getPendingProducts().edit();
        edit.putBoolean(str, true);
        edit.commit();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void download(final Product product, String str) {
        File filesDir;
        final String identifier = product.getIdentifier();
        String title = product.getTitle();
        String sanitize = sanitize(identifier);
        Request request = new Request("GET", str);
        product.setStatus(Product.Status.DOWNLOADING);
        PurchaseNotificationInfo purchaseNotificationInfo = this.notificationController.get(identifier);
        purchaseNotificationInfo.setNotificationType(PurchaseNotificationInfo.NotificationType.DOWNLOADING);
        this.notificationController.sendNotification(purchaseNotificationInfo);
        try {
            if (Environment.getExternalStorageState().equals("mounted")) {
                filesDir = Environment.getExternalStorageDirectory();
                Logger.debug("Writing to SD card");
            } else {
                filesDir = UAirship.shared().getApplicationContext().getFilesDir();
                Logger.info("SD card not available, writing to internal storage");
            }
            final File canonicalFile = new File(filesDir, IAPManager.shared().getTempPath() + sanitize + ".zip").getCanonicalFile();
            final File canonicalFile2 = new File(filesDir, IAPManager.shared().getDownloadPath() + sanitize).getCanonicalFile();
            request.setDestination(canonicalFile);
            this.queue.addRequest(request, new AsyncHandler() { // from class: com.urbanairship.iap.DownloadManager.2
                @Override // com.urbanairship.restclient.AsyncHandler
                public void onComplete(Response response) {
                    Logger.info("Downloaded product to " + canonicalFile + ", extracting...");
                    PurchaseNotificationInfo purchaseNotificationInfo2 = DownloadManager.this.notificationController.get(identifier);
                    purchaseNotificationInfo2.setProgress(100);
                    IAPEventListener eventListener = IAPManager.shared().getEventListener();
                    if (eventListener != null) {
                        eventListener.downloadProgress(product, 100);
                    }
                    purchaseNotificationInfo2.setNotificationType(PurchaseNotificationInfo.NotificationType.DECOMPRESSING);
                    DownloadManager.this.notificationController.sendNotification(purchaseNotificationInfo2);
                    UnzipperTask unzipperTask = new UnzipperTask();
                    unzipperTask.setDelegate(new UnzipDelegate(product, canonicalFile2));
                    unzipperTask.execute(canonicalFile, canonicalFile2);
                }

                @Override // com.urbanairship.restclient.AsyncHandler
                public void onError(Exception exc) {
                    Logger.error("Download " + product + " failed", exc);
                    DownloadManager.this.retry(product);
                }

                @Override // com.urbanairship.restclient.AsyncHandler
                public void onProgress(int i) {
                    Logger.verbose("Download " + product + " progress " + i);
                    PurchaseNotificationInfo purchaseNotificationInfo2 = DownloadManager.this.notificationController.get(identifier);
                    purchaseNotificationInfo2.setProgress(i);
                    DownloadManager.this.notificationController.sendNotification(purchaseNotificationInfo2);
                    IAPEventListener eventListener = IAPManager.shared().getEventListener();
                    if (eventListener != null) {
                        eventListener.downloadProgress(product, i);
                    }
                }
            });
        } catch (Exception e) {
            Logger.error("Error downloading product " + title, e);
            retry(product);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void removePendingProduct(String str) {
        SharedPreferences.Editor edit = getPendingProducts().edit();
        edit.remove(str);
        edit.commit();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void resumePendingProducts() {
        Logger.verbose("resumePendingProducts");
        for (Map.Entry<String, ?> entry : getPendingProducts().getAll().entrySet()) {
            Product product = IAPManager.shared().getInventory().getProduct(entry.getKey());
            String title = product.getTitle();
            Product.Status status = product.getStatus();
            if (status == Product.Status.DOWNLOADING || status == Product.Status.WAITING) {
                Logger.info(title + " is already downloading");
            } else {
                Logger.info("resuming download of " + title);
                verify(product);
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void retry(Product product) {
        String identifier = product.getIdentifier();
        String title = product.getTitle();
        int intValue = this.tries.get(identifier).intValue();
        product.setStatus(Product.Status.PURCHASED);
        if (this.tries.get(identifier).intValue() < 3) {
            this.tries.put(identifier, Integer.valueOf(intValue + 1));
            Logger.info("Retrying download of " + title);
            verify(product);
            return;
        }
        Logger.info(String.format("Already tried downloading %s %d times, giving up for now", title, 3));
        this.notificationController.get(identifier).setNotificationType(PurchaseNotificationInfo.NotificationType.DOWNLOAD_FAILED);
        this.notificationController.removePurchaseNotification(identifier);
        this.tries.remove(identifier);
        IAPEventListener eventListener = IAPManager.shared().getEventListener();
        if (eventListener != null) {
            eventListener.downloadFailed(product);
        }
    }

    private String sanitize(String str) {
        String trim = str.trim();
        while (!trim.substring(trim.length() - 1).matches("[a-zA-Z0-9]")) {
            trim = trim.substring(0, trim.length() - 1);
        }
        return trim;
    }

    private void verify(final Product product) {
        String identifier = product.getIdentifier();
        final String title = product.getTitle();
        product.setStatus(Product.Status.WAITING);
        if (!this.notificationController.contains(identifier)) {
            this.notificationController.registerPurchaseNotification(identifier, title, PurchaseNotificationInfo.NotificationType.VERIFYING_RECEIPT);
        }
        if (!this.tries.containsKey(identifier)) {
            this.tries.put(identifier, 1);
        }
        AppAuthenticatedRequest appAuthenticatedRequest = new AppAuthenticatedRequest("POST", product.getDownloadURLString() + "?platform=android");
        Receipt fetch = Receipt.fetch(identifier);
        String signedData = fetch.getSignedData();
        String signature = fetch.getSignature();
        if (signedData == null || signature == null) {
            Logger.debug("free product, sending bare request");
        } else {
            Logger.debug("paid product, verifying receipt");
            Logger.debug("receipt: " + signedData + " signature: " + signature);
            try {
                StringEntity stringEntity = new StringEntity(signedData, "UTF-8");
                stringEntity.setContentType("application/json");
                appAuthenticatedRequest.setEntity(stringEntity);
            } catch (UnsupportedEncodingException e) {
                Logger.error("Error setting verifyRequest entity");
            }
            appAuthenticatedRequest.addHeader(new BasicHeader("x-google-iap-signature", signature));
        }
        this.queue.addRequest(appAuthenticatedRequest, new AsyncHandler() { // from class: com.urbanairship.iap.DownloadManager.1
            @Override // com.urbanairship.restclient.AsyncHandler
            public void onComplete(Response response) {
                String body = response.body();
                Logger.verbose("verifyRequest result " + body);
                if (response.status() != 200) {
                    Logger.debug("verifyRequest response status: " + response.status());
                    DownloadManager.this.retry(product);
                    return;
                }
                try {
                    DownloadManager.this.download(product, ((JSONObject) new JSONTokener(body).nextValue()).getString("content_url"));
                } catch (Exception e2) {
                    Logger.error("Error parsing verification response from server, for product " + title);
                    DownloadManager.this.retry(product);
                }
            }

            @Override // com.urbanairship.restclient.AsyncHandler
            public void onError(Exception exc) {
                Logger.error("Error fetching content url from server, for product: " + product);
                DownloadManager.this.retry(product);
            }
        });
        this.notificationController.sendNotification(this.notificationController.get(identifier));
        IAPEventListener eventListener = IAPManager.shared().getEventListener();
        if (eventListener != null) {
            eventListener.downloadStarted(product, this.tries.get(identifier).intValue());
        }
    }

    public void downloadIfValid(Product product) {
        String identifier = product.getIdentifier();
        if (!hasPendingProduct(identifier)) {
            addPendingProduct(identifier);
        }
        verify(product);
    }

    SharedPreferences getPendingProducts() {
        return UAirship.shared().getApplicationContext().getSharedPreferences(PENDING_PRODUCTS_FILE, 0);
    }

    public boolean hasPendingProduct(String str) {
        return getPendingProducts().contains(str);
    }
}
