package okhttp3.internal.ws;

import c.k;
import c.q.d.g;
import c.q.d.j;
import c.u.n;
import d.h;
import d.i;
import d.p;
import java.io.Closeable;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.EventListener;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.RealCall;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okhttp3.internal.Util;
import okhttp3.internal.connection.Exchange;
import okhttp3.internal.ws.WebSocketReader;
import org.eclipse.paho.android.service.MqttServiceConstants;

/* JADX INFO: compiled from: RealWebSocket.kt */
/* JADX INFO: loaded from: classes.dex */
public final class RealWebSocket implements WebSocket, WebSocketReader.FrameCallback {
    private static final long CANCEL_AFTER_CLOSE_MILLIS = 60000;
    private static final long MAX_QUEUE_SIZE = 16777216;
    private boolean awaitingPong;
    private Call call;
    private ScheduledFuture<?> cancelFuture;
    private boolean enqueuedClose;
    private ScheduledExecutorService executor;
    private boolean failed;
    private final String key;
    private final WebSocketListener listener;
    private final ArrayDeque<Object> messageAndCloseQueue;
    private final Request originalRequest;
    private final long pingIntervalMillis;
    private final ArrayDeque<i> pongQueue;
    private long queueSize;
    private final Random random;
    private WebSocketReader reader;
    private int receivedCloseCode;
    private String receivedCloseReason;
    private int receivedPingCount;
    private int receivedPongCount;
    private int sentPingCount;
    private Streams streams;
    private WebSocketWriter writer;
    private final Runnable writerRunnable;
    public static final Companion Companion = new Companion(null);
    private static final List<Protocol> ONLY_HTTP1 = c.l.i.b(Protocol.HTTP_1_1);

    /* JADX INFO: compiled from: RealWebSocket.kt */
    public final class CancelRunnable implements Runnable {
        public CancelRunnable() {
        }

        @Override // java.lang.Runnable
        public void run() {
            RealWebSocket.this.cancel();
        }
    }

    /* JADX INFO: compiled from: RealWebSocket.kt */
    public static final class Close {
        private final long cancelAfterCloseMillis;
        private final int code;
        private final i reason;

        public Close(int i, i iVar, long j) {
            this.code = i;
            this.reason = iVar;
            this.cancelAfterCloseMillis = j;
        }

        public final long getCancelAfterCloseMillis() {
            return this.cancelAfterCloseMillis;
        }

        public final int getCode() {
            return this.code;
        }

        public final i getReason() {
            return this.reason;
        }
    }

    /* JADX INFO: compiled from: RealWebSocket.kt */
    public static final class Companion {
        private Companion() {
        }

        public /* synthetic */ Companion(g gVar) {
            this();
        }
    }

    /* JADX INFO: compiled from: RealWebSocket.kt */
    public static final class Message {
        private final i data;
        private final int formatOpcode;

        public Message(int i, i iVar) {
            j.c(iVar, "data");
            this.formatOpcode = i;
            this.data = iVar;
        }

        public final i getData() {
            return this.data;
        }

        public final int getFormatOpcode() {
            return this.formatOpcode;
        }
    }

    /* JADX INFO: compiled from: RealWebSocket.kt */
    private final class PingRunnable implements Runnable {
        public PingRunnable() {
        }

        @Override // java.lang.Runnable
        public void run() {
            RealWebSocket.this.writePingFrame$okhttp();
        }
    }

    /* JADX INFO: compiled from: RealWebSocket.kt */
    public static abstract class Streams implements Closeable {
        private final boolean client;
        private final d.g sink;
        private final h source;

        public Streams(boolean z, h hVar, d.g gVar) {
            j.c(hVar, "source");
            j.c(gVar, "sink");
            this.client = z;
            this.source = hVar;
            this.sink = gVar;
        }

        public final boolean getClient() {
            return this.client;
        }

        public final d.g getSink() {
            return this.sink;
        }

        public final h getSource() {
            return this.source;
        }
    }

    public RealWebSocket(Request request, WebSocketListener webSocketListener, Random random, long j) {
        j.c(request, "originalRequest");
        j.c(webSocketListener, "listener");
        j.c(random, "random");
        this.originalRequest = request;
        this.listener = webSocketListener;
        this.random = random;
        this.pingIntervalMillis = j;
        this.pongQueue = new ArrayDeque<>();
        this.messageAndCloseQueue = new ArrayDeque<>();
        this.receivedCloseCode = -1;
        if (!j.a("GET", this.originalRequest.method())) {
            throw new IllegalArgumentException(("Request must be GET: " + this.originalRequest.method()).toString());
        }
        i.a aVar = i.f1573f;
        byte[] bArr = new byte[16];
        this.random.nextBytes(bArr);
        this.key = i.a.g(aVar, bArr, 0, 0, 3, null).a();
        this.writerRunnable = new Runnable() { // from class: okhttp3.internal.ws.RealWebSocket.3
            @Override // java.lang.Runnable
            public final void run() {
                do {
                    try {
                    } catch (IOException e2) {
                        RealWebSocket.this.failWebSocket(e2, null);
                        return;
                    }
                } while (RealWebSocket.this.writeOneFrame$okhttp());
            }
        };
    }

    private final void runWriter() {
        boolean zHoldsLock = Thread.holdsLock(this);
        if (k.f1418a && !zHoldsLock) {
            throw new AssertionError("Assertion failed");
        }
        ScheduledExecutorService scheduledExecutorService = this.executor;
        if (scheduledExecutorService != null) {
            scheduledExecutorService.execute(this.writerRunnable);
        }
    }

    public final void awaitTermination(int i, TimeUnit timeUnit) throws InterruptedException {
        j.c(timeUnit, "timeUnit");
        ScheduledExecutorService scheduledExecutorService = this.executor;
        if (scheduledExecutorService != null) {
            scheduledExecutorService.awaitTermination(i, timeUnit);
        } else {
            j.g();
            throw null;
        }
    }

    @Override // okhttp3.WebSocket
    public void cancel() {
        Call call = this.call;
        if (call != null) {
            call.cancel();
        } else {
            j.g();
            throw null;
        }
    }

    public final void checkUpgradeSuccess$okhttp(Response response, Exchange exchange) throws IOException {
        j.c(response, "response");
        if (response.code() != 101) {
            throw new ProtocolException("Expected HTTP 101 response but was '" + response.code() + ' ' + response.message() + '\'');
        }
        String strHeader$default = Response.header$default(response, "Connection", null, 2, null);
        if (!n.h("Upgrade", strHeader$default, true)) {
            throw new ProtocolException("Expected 'Connection' header value 'Upgrade' but was '" + strHeader$default + '\'');
        }
        String strHeader$default2 = Response.header$default(response, "Upgrade", null, 2, null);
        if (!n.h("websocket", strHeader$default2, true)) {
            throw new ProtocolException("Expected 'Upgrade' header value 'websocket' but was '" + strHeader$default2 + '\'');
        }
        String strHeader$default3 = Response.header$default(response, "Sec-WebSocket-Accept", null, 2, null);
        String strA = i.f1573f.d(this.key + WebSocketProtocol.ACCEPT_MAGIC).q().a();
        if (!(!j.a(strA, strHeader$default3))) {
            if (exchange == null) {
                throw new ProtocolException("Web Socket exchange missing: bad interceptor?");
            }
            return;
        }
        throw new ProtocolException("Expected 'Sec-WebSocket-Accept' header value '" + strA + "' but was '" + strHeader$default3 + '\'');
    }

    @Override // okhttp3.WebSocket
    public boolean close(int i, String str) {
        return close(i, str, CANCEL_AFTER_CLOSE_MILLIS);
    }

    public final void connect(OkHttpClient okHttpClient) {
        j.c(okHttpClient, "client");
        OkHttpClient okHttpClientBuild = okHttpClient.newBuilder().eventListener(EventListener.NONE).protocols(ONLY_HTTP1).build();
        final Request requestBuild = this.originalRequest.newBuilder().header("Upgrade", "websocket").header("Connection", "Upgrade").header("Sec-WebSocket-Key", this.key).header("Sec-WebSocket-Version", "13").build();
        RealCall realCallNewRealCall = RealCall.Companion.newRealCall(okHttpClientBuild, requestBuild, true);
        this.call = realCallNewRealCall;
        if (realCallNewRealCall != null) {
            realCallNewRealCall.enqueue(new Callback() { // from class: okhttp3.internal.ws.RealWebSocket.connect.1
                @Override // okhttp3.Callback
                public void onFailure(Call call, IOException iOException) {
                    j.c(call, "call");
                    j.c(iOException, "e");
                    RealWebSocket.this.failWebSocket(iOException, null);
                }

                @Override // okhttp3.Callback
                public void onResponse(Call call, Response response) {
                    j.c(call, "call");
                    j.c(response, "response");
                    Exchange exchange = response.exchange();
                    try {
                        RealWebSocket.this.checkUpgradeSuccess$okhttp(response, exchange);
                        if (exchange == null) {
                            j.g();
                            throw null;
                        }
                        try {
                            RealWebSocket.this.initReaderAndWriter("OkHttp WebSocket " + requestBuild.url().redact(), exchange.newWebSocketStreams());
                            RealWebSocket.this.getListener$okhttp().onOpen(RealWebSocket.this, response);
                            RealWebSocket.this.loopReader();
                        } catch (Exception e2) {
                            RealWebSocket.this.failWebSocket(e2, null);
                        }
                    } catch (IOException e3) {
                        if (exchange != null) {
                            exchange.webSocketUpgradeFailed();
                        }
                        RealWebSocket.this.failWebSocket(e3, response);
                        Util.closeQuietly(response);
                    }
                }
            });
        } else {
            j.g();
            throw null;
        }
    }

    public final void failWebSocket(Exception exc, Response response) {
        j.c(exc, "e");
        synchronized (this) {
            if (this.failed) {
                return;
            }
            this.failed = true;
            Streams streams = this.streams;
            this.streams = null;
            ScheduledFuture<?> scheduledFuture = this.cancelFuture;
            if (scheduledFuture != null) {
                scheduledFuture.cancel(false);
            }
            ScheduledExecutorService scheduledExecutorService = this.executor;
            if (scheduledExecutorService != null) {
                scheduledExecutorService.shutdown();
                c.j jVar = c.j.f1417a;
            }
            try {
                this.listener.onFailure(this, exc, response);
            } finally {
                if (streams != null) {
                    Util.closeQuietly(streams);
                }
            }
        }
    }

    public final WebSocketListener getListener$okhttp() {
        return this.listener;
    }

    public final void initReaderAndWriter(String str, Streams streams) throws IOException {
        j.c(str, "name");
        j.c(streams, "streams");
        synchronized (this) {
            this.streams = streams;
            this.writer = new WebSocketWriter(streams.getClient(), streams.getSink(), this.random);
            ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1, Util.threadFactory(str, false));
            this.executor = scheduledThreadPoolExecutor;
            if (this.pingIntervalMillis != 0) {
                if (scheduledThreadPoolExecutor == null) {
                    j.g();
                    throw null;
                }
                scheduledThreadPoolExecutor.scheduleAtFixedRate(new PingRunnable(), this.pingIntervalMillis, this.pingIntervalMillis, TimeUnit.MILLISECONDS);
            }
            if (!this.messageAndCloseQueue.isEmpty()) {
                runWriter();
            }
            c.j jVar = c.j.f1417a;
        }
        this.reader = new WebSocketReader(streams.getClient(), streams.getSource(), this);
    }

    public final void loopReader() throws IOException {
        while (this.receivedCloseCode == -1) {
            WebSocketReader webSocketReader = this.reader;
            if (webSocketReader == null) {
                j.g();
                throw null;
            }
            webSocketReader.processNextFrame();
        }
    }

    @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback
    public void onReadClose(int i, String str) {
        Streams streams;
        j.c(str, "reason");
        boolean z = true;
        if (!(i != -1)) {
            throw new IllegalArgumentException("Failed requirement.".toString());
        }
        synchronized (this) {
            if (this.receivedCloseCode != -1) {
                z = false;
            }
            if (!z) {
                throw new IllegalStateException("already closed".toString());
            }
            this.receivedCloseCode = i;
            this.receivedCloseReason = str;
            streams = null;
            if (this.enqueuedClose && this.messageAndCloseQueue.isEmpty()) {
                Streams streams2 = this.streams;
                this.streams = null;
                if (this.cancelFuture != null) {
                    ScheduledFuture<?> scheduledFuture = this.cancelFuture;
                    if (scheduledFuture == null) {
                        j.g();
                        throw null;
                    }
                    scheduledFuture.cancel(false);
                }
                ScheduledExecutorService scheduledExecutorService = this.executor;
                if (scheduledExecutorService == null) {
                    j.g();
                    throw null;
                }
                scheduledExecutorService.shutdown();
                streams = streams2;
            }
            c.j jVar = c.j.f1417a;
        }
        try {
            this.listener.onClosing(this, i, str);
            if (streams != null) {
                this.listener.onClosed(this, i, str);
            }
        } finally {
            if (streams != null) {
                Util.closeQuietly(streams);
            }
        }
    }

    @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback
    public void onReadMessage(String str) throws IOException {
        j.c(str, "text");
        this.listener.onMessage(this, str);
    }

    @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback
    public synchronized void onReadPing(i iVar) {
        j.c(iVar, MqttServiceConstants.PAYLOAD);
        if (!this.failed && (!this.enqueuedClose || !this.messageAndCloseQueue.isEmpty())) {
            this.pongQueue.add(iVar);
            runWriter();
            this.receivedPingCount++;
        }
    }

    @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback
    public synchronized void onReadPong(i iVar) {
        j.c(iVar, MqttServiceConstants.PAYLOAD);
        this.receivedPongCount++;
        this.awaitingPong = false;
    }

    public final synchronized boolean pong(i iVar) {
        j.c(iVar, MqttServiceConstants.PAYLOAD);
        if (!this.failed && (!this.enqueuedClose || !this.messageAndCloseQueue.isEmpty())) {
            this.pongQueue.add(iVar);
            runWriter();
            return true;
        }
        return false;
    }

    public final boolean processNextFrame() throws IOException {
        try {
            WebSocketReader webSocketReader = this.reader;
            if (webSocketReader != null) {
                webSocketReader.processNextFrame();
                return this.receivedCloseCode == -1;
            }
            j.g();
            throw null;
        } catch (Exception e2) {
            failWebSocket(e2, null);
            return false;
        }
    }

    @Override // okhttp3.WebSocket
    public synchronized long queueSize() {
        return this.queueSize;
    }

    public final synchronized int receivedPingCount() {
        return this.receivedPingCount;
    }

    public final synchronized int receivedPongCount() {
        return this.receivedPongCount;
    }

    @Override // okhttp3.WebSocket
    public Request request() {
        return this.originalRequest;
    }

    @Override // okhttp3.WebSocket
    public boolean send(String str) {
        j.c(str, "text");
        return send(i.f1573f.d(str), 1);
    }

    public final synchronized int sentPingCount() {
        return this.sentPingCount;
    }

    public final void tearDown() throws InterruptedException {
        ScheduledFuture<?> scheduledFuture = this.cancelFuture;
        if (scheduledFuture != null) {
            if (scheduledFuture == null) {
                j.g();
                throw null;
            }
            scheduledFuture.cancel(false);
        }
        ScheduledExecutorService scheduledExecutorService = this.executor;
        if (scheduledExecutorService == null) {
            j.g();
            throw null;
        }
        scheduledExecutorService.shutdown();
        ScheduledExecutorService scheduledExecutorService2 = this.executor;
        if (scheduledExecutorService2 != null) {
            scheduledExecutorService2.awaitTermination(10L, TimeUnit.SECONDS);
        } else {
            j.g();
            throw null;
        }
    }

    public final boolean writeOneFrame$okhttp() throws IOException {
        int i;
        Streams streams;
        Object objPoll;
        String str;
        synchronized (this) {
            if (this.failed) {
                return false;
            }
            WebSocketWriter webSocketWriter = this.writer;
            i iVarPoll = this.pongQueue.poll();
            if (iVarPoll == null) {
                objPoll = this.messageAndCloseQueue.poll();
                if (objPoll instanceof Close) {
                    i = this.receivedCloseCode;
                    str = this.receivedCloseReason;
                    if (i != -1) {
                        streams = this.streams;
                        this.streams = null;
                        ScheduledExecutorService scheduledExecutorService = this.executor;
                        if (scheduledExecutorService == null) {
                            j.g();
                            throw null;
                        }
                        scheduledExecutorService.shutdown();
                    } else {
                        ScheduledExecutorService scheduledExecutorService2 = this.executor;
                        if (scheduledExecutorService2 == null) {
                            j.g();
                            throw null;
                        }
                        this.cancelFuture = scheduledExecutorService2.schedule(new CancelRunnable(), ((Close) objPoll).getCancelAfterCloseMillis(), TimeUnit.MILLISECONDS);
                        streams = null;
                    }
                } else {
                    if (objPoll == null) {
                        return false;
                    }
                    i = -1;
                    streams = null;
                    str = null;
                }
            } else {
                i = -1;
                streams = null;
                objPoll = null;
                str = null;
            }
            c.j jVar = c.j.f1417a;
            try {
                if (iVarPoll != null) {
                    if (webSocketWriter == null) {
                        j.g();
                        throw null;
                    }
                    webSocketWriter.writePong(iVarPoll);
                } else if (objPoll instanceof Message) {
                    i data = ((Message) objPoll).getData();
                    if (webSocketWriter == null) {
                        j.g();
                        throw null;
                    }
                    d.g gVarC = p.c(webSocketWriter.newMessageSink(((Message) objPoll).getFormatOpcode(), data.s()));
                    gVarC.d(data);
                    gVarC.close();
                    synchronized (this) {
                        this.queueSize -= (long) data.s();
                        c.j jVar2 = c.j.f1417a;
                    }
                } else {
                    if (!(objPoll instanceof Close)) {
                        throw new AssertionError();
                    }
                    Close close = (Close) objPoll;
                    if (webSocketWriter == null) {
                        j.g();
                        throw null;
                    }
                    webSocketWriter.writeClose(close.getCode(), close.getReason());
                    if (streams != null) {
                        WebSocketListener webSocketListener = this.listener;
                        if (str == null) {
                            j.g();
                            throw null;
                        }
                        webSocketListener.onClosed(this, i, str);
                    }
                }
                return true;
            } finally {
                if (streams != null) {
                    Util.closeQuietly(streams);
                }
            }
        }
    }

    public final void writePingFrame$okhttp() {
        synchronized (this) {
            if (this.failed) {
                return;
            }
            WebSocketWriter webSocketWriter = this.writer;
            int i = this.awaitingPong ? this.sentPingCount : -1;
            this.sentPingCount++;
            this.awaitingPong = true;
            c.j jVar = c.j.f1417a;
            if (i != -1) {
                failWebSocket(new SocketTimeoutException("sent ping but didn't receive pong within " + this.pingIntervalMillis + "ms (after " + (i - 1) + " successful ping/pongs)"), null);
                return;
            }
            try {
                if (webSocketWriter != null) {
                    webSocketWriter.writePing(i.f1572e);
                } else {
                    j.g();
                    throw null;
                }
            } catch (IOException e2) {
                failWebSocket(e2, null);
            }
        }
    }

    public final synchronized boolean close(int i, String str, long j) {
        WebSocketProtocol.INSTANCE.validateCloseCode(i);
        i iVarD = null;
        if (str != null) {
            iVarD = i.f1573f.d(str);
            if (!(((long) iVarD.s()) <= 123)) {
                throw new IllegalArgumentException(("reason.size() > 123: " + str).toString());
            }
        }
        if (!this.failed && !this.enqueuedClose) {
            this.enqueuedClose = true;
            this.messageAndCloseQueue.add(new Close(i, iVarD, j));
            runWriter();
            return true;
        }
        return false;
    }

    @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback
    public void onReadMessage(i iVar) throws IOException {
        j.c(iVar, "bytes");
        this.listener.onMessage(this, iVar);
    }

    @Override // okhttp3.WebSocket
    public boolean send(i iVar) {
        j.c(iVar, "bytes");
        return send(iVar, 2);
    }

    private final synchronized boolean send(i iVar, int i) {
        if (!this.failed && !this.enqueuedClose) {
            if (this.queueSize + ((long) iVar.s()) > MAX_QUEUE_SIZE) {
                close(WebSocketProtocol.CLOSE_CLIENT_GOING_AWAY, null);
                return false;
            }
            this.queueSize += (long) iVar.s();
            this.messageAndCloseQueue.add(new Message(i, iVar));
            runWriter();
            return true;
        }
        return false;
    }
}
