package com.urbanairship.push.embedded;

import com.flurry.org.codehaus.jackson.util.MinimalPrettyPrinter;
import com.google.protobuf.InvalidProtocolBufferException;
import com.urbanairship.Logger;
import com.urbanairship.push.PushManager;
import com.urbanairship.push.embedded.BoxOfficeClient;
import com.urbanairship.push.embedded.Config;
import com.urbanairship.push.embedded.HeliumClient;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
public class HeliumConnection extends Thread {
    public static final int CONNECTION_TIMEOUT = 60000;
    private BoxOfficeClient boxOffice;
    private HeliumClient helium;
    private EmbeddedPushManager manager;
    private Socket socket;
    private long retryInterval = 10000;
    private AtomicBoolean running = new AtomicBoolean(false);
    private AtomicLong lastSocketActivity = new AtomicLong(0);

    public HeliumConnection(EmbeddedPushManager embeddedPushManager, BoxOfficeClient boxOfficeClient) {
        this.manager = embeddedPushManager;
        this.boxOffice = boxOfficeClient;
        setName("HeliumConnectionThread");
    }

    private void close(Socket socket) {
        if (socket != null) {
            try {
                if (!socket.isConnected() || socket.isClosed()) {
                    return;
                }
                socket.close();
            } catch (IOException e) {
                Logger.warn("Error closing socket.");
            }
        }
    }

    private boolean sleepForRetryInterval(long j) {
        long min = System.currentTimeMillis() - j < Config.Helium.retryResetThreshold ? Math.min(this.retryInterval * 2, (long) Config.Helium.maxRetryInterval) : 10000L;
        Logger.debug("Rescheduling connection in " + min + "ms.");
        this.retryInterval = min;
        try {
            Thread.sleep(min);
            return true;
        } catch (InterruptedException e) {
            return false;
        }
    }

    public void abort() {
        Logger.debug("Connection aborting.");
        this.running.set(false);
        Logger.debug("Closing socket.");
        if (this.socket != null) {
            close(this.socket);
        }
        Logger.debug("Service stopped, socket closed successfully.");
    }

    public long getRetryInterval() {
        return this.retryInterval;
    }

    public boolean isConnected() {
        return (this.socket == null || !this.socket.isConnected() || this.socket.isClosed()) ? false : true;
    }

    public boolean isRunning() {
        return this.running.get();
    }

    public boolean isSocketStale() {
        Logger.verbose("Checking socket status:");
        if (!isRunning()) {
            Logger.verbose("The connection is not running.");
            return false;
        } else if (this.socket == null) {
            Logger.verbose("Socket is null.");
            return false;
        } else if (!this.socket.isConnected()) {
            Logger.verbose("Socket is not connected.");
            return false;
        } else if (this.socket.isClosed()) {
            Logger.verbose("Socket is closed.");
            return false;
        } else if (System.currentTimeMillis() - this.lastSocketActivity.get() > Config.Helium.max_keepalive_interval) {
            return true;
        } else {
            Logger.verbose("Connected to Helium with a healthy socket.");
            return false;
        }
    }

    public void resetStaleConnection() {
        if (isSocketStale()) {
            Logger.verbose("Helium connection is stale. Closing socket to force retry.");
            close(this.socket);
        }
    }

    @Override // java.lang.Thread, java.lang.Runnable
    public void run() {
        String lookup;
        Logger.verbose("HeliumConnection - run");
        this.running.set(true);
        while (isRunning()) {
            String typeName = Network.typeName();
            try {
                lookup = this.boxOffice.lookup();
            } catch (BoxOfficeClient.FirstRunForbiddenException e) {
                Logger.error(e.getMessage());
                EmbeddedPushManager.shared().stopHeartBeat();
                PushManager.stopService();
                this.running.set(false);
                return;
            } catch (BoxOfficeClient.FatalBoxOfficeException e2) {
                Logger.error(e2.getMessage());
                PushManager.stopService();
                this.running.set(false);
                return;
            } catch (BoxOfficeClient.BoxOfficeException e3) {
                Logger.error(e3.getMessage());
                if (!sleepForRetryInterval(System.currentTimeMillis())) {
                    this.running.set(false);
                    return;
                }
            }
            if (lookup == null) {
                throw new BoxOfficeClient.BoxOfficeException("No Helium servers available for connection.");
            }
            if (Thread.interrupted()) {
                Logger.debug("Thread interrupted during lookup.");
                this.running.set(false);
                return;
            }
            String[] split = lookup.split(":");
            String str = split[0];
            Integer num = new Integer(split[1]);
            if (!isRunning()) {
                Logger.debug("Connection sequence aborted. Ending prior to opening Helium connection.");
                return;
            }
            Logger.debug("Connecting to " + str + ":" + num);
            long currentTimeMillis = System.currentTimeMillis();
            try {
                try {
                    try {
                        try {
                            try {
                                try {
                                    this.socket = new Socket();
                                    this.socket.setTcpNoDelay(false);
                                    this.socket.setSoTimeout((int) Config.Helium.max_keepalive_interval);
                                    this.lastSocketActivity.set(System.currentTimeMillis());
                                    this.socket.connect(new InetSocketAddress(str, num.intValue()), 60000);
                                    Logger.info("Connection established to " + this.socket.getInetAddress() + ":" + num + " on network type " + typeName);
                                    this.helium = new HeliumClient(this.socket, this.boxOffice);
                                    this.helium.register();
                                    while (isRunning()) {
                                        this.helium.readResponse();
                                        this.lastSocketActivity.set(System.currentTimeMillis());
                                        Thread.sleep(100L);
                                    }
                                    if (isRunning()) {
                                        close(this.socket);
                                        if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                                            this.running.set(false);
                                        } else {
                                            this.boxOffice.incrementFailureCount();
                                            if (!sleepForRetryInterval(currentTimeMillis)) {
                                                this.running.set(false);
                                                return;
                                            }
                                        }
                                    } else {
                                        Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                                    }
                                } catch (IOException e4) {
                                    Logger.debug("IOException (Expected following restart or connectivity change).");
                                    if (isRunning()) {
                                        close(this.socket);
                                        if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                                            this.running.set(false);
                                        } else {
                                            this.boxOffice.incrementFailureCount();
                                            if (!sleepForRetryInterval(currentTimeMillis)) {
                                                this.running.set(false);
                                                return;
                                            }
                                        }
                                    } else {
                                        Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                                    }
                                }
                            } catch (Exception e5) {
                                Logger.debug("Exception in Helium connection. Network type=" + typeName + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + e5.getMessage());
                                if (isRunning()) {
                                    close(this.socket);
                                    if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                                        this.running.set(false);
                                    } else {
                                        this.boxOffice.incrementFailureCount();
                                        if (!sleepForRetryInterval(currentTimeMillis)) {
                                            this.running.set(false);
                                            return;
                                        }
                                    }
                                } else {
                                    Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                                }
                            }
                        } catch (HeliumClient.HeliumInvalidPackageException e6) {
                            Logger.error(e6.getMessage());
                            EmbeddedPushManager.shared().stopHeartBeat();
                            PushManager.stopService();
                            EmbeddedPushManager.sendRegistrationResponse(false);
                            this.running.set(false);
                            if (!isRunning()) {
                                Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                                return;
                            }
                            close(this.socket);
                            if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                                this.running.set(false);
                                return;
                            }
                            this.boxOffice.incrementFailureCount();
                            if (!sleepForRetryInterval(currentTimeMillis)) {
                                this.running.set(false);
                                return;
                            }
                        }
                    } catch (HeliumClient.HeliumException e7) {
                        Logger.debug("Helium exception - secret not set.");
                        if (isRunning()) {
                            close(this.socket);
                            if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                                this.running.set(false);
                            } else {
                                this.boxOffice.incrementFailureCount();
                                if (!sleepForRetryInterval(currentTimeMillis)) {
                                    this.running.set(false);
                                    return;
                                }
                            }
                        } else {
                            Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                        }
                    } catch (InterruptedIOException e8) {
                        Logger.debug("Socket timed out.");
                        if (isRunning()) {
                            close(this.socket);
                            if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                                this.running.set(false);
                            } else {
                                this.boxOffice.incrementFailureCount();
                                if (!sleepForRetryInterval(currentTimeMillis)) {
                                    this.running.set(false);
                                    return;
                                }
                            }
                        } else {
                            Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                        }
                    }
                } catch (InterruptedException e9) {
                    Logger.debug("Connection thread interrupted.");
                    this.running.set(false);
                    if (!isRunning()) {
                        Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                        return;
                    }
                    close(this.socket);
                    if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                        this.running.set(false);
                        return;
                    }
                    this.boxOffice.incrementFailureCount();
                    if (!sleepForRetryInterval(currentTimeMillis)) {
                        this.running.set(false);
                        return;
                    }
                } catch (InvalidProtocolBufferException e10) {
                    Logger.debug("Invalid protobuf exception (Expected, likely due to socket interruption).");
                    if (isRunning()) {
                        close(this.socket);
                        if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                            this.running.set(false);
                        } else {
                            this.boxOffice.incrementFailureCount();
                            if (!sleepForRetryInterval(currentTimeMillis)) {
                                this.running.set(false);
                                return;
                            }
                        }
                    } else {
                        Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                    }
                }
            } catch (Throwable th) {
                if (isRunning()) {
                    close(this.socket);
                    if (!Network.isConnected() || this.manager.isInHoldingPattern()) {
                        this.running.set(false);
                    } else {
                        this.boxOffice.incrementFailureCount();
                        if (!sleepForRetryInterval(currentTimeMillis)) {
                            this.running.set(false);
                            return;
                        }
                    }
                } else {
                    Logger.debug("Connection aborted, shutting down. Network type=" + typeName);
                }
                throw th;
            }
        }
    }

    public void setRetryInterval(long j) {
        this.retryInterval = Math.min(j, (long) Config.Helium.maxRetryInterval);
    }
}
