package com.discord.gateway; import android.content.Context; import c.d.b.a.a; import c.i.d.c; import c.i.d.e; import com.discord.api.activity.Activity; import com.discord.api.activity.ActivityType; import com.discord.api.activity.ActivityTypeTypeAdapter; import com.discord.api.channel.Channel; import com.discord.api.guild.Guild; import com.discord.api.presence.ClientStatus; import com.discord.gateway.GatewaySocketLogger; import com.discord.gateway.io.Incoming; import com.discord.gateway.io.IncomingParser; import com.discord.gateway.io.Outgoing; import com.discord.gateway.io.OutgoingPayload; import com.discord.gateway.opcodes.Opcode; import com.discord.gateway.rest.RestClient; import com.discord.gateway.rest.RestConfig; import com.discord.models.domain.Model; import com.discord.models.domain.ModelPayload; import com.discord.utilities.logging.Logger; import com.discord.utilities.networking.Backoff; import com.discord.utilities.networking.NetworkMonitor; import com.discord.utilities.time.Clock; import com.discord.utilities.time.ClockFactory; import com.discord.utilities.websocket.WebSocket; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import d0.t.h0; import d0.t.n0; import d0.t.u; import d0.z.d.e0; import d0.z.d.m; import d0.z.d.o; import j0.k.b; import j0.l.a.r; import j0.l.a.v1; import j0.l.a.w1; import j0.l.e.j; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLSocketFactory; import kotlin.NoWhenBranchMatchedException; import kotlin.Pair; import kotlin.Unit; import kotlin.jvm.functions.Function0; import kotlin.jvm.functions.Function1; import kotlin.jvm.internal.DefaultConstructorMarker; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.functions.Action1; /* compiled from: GatewaySocket.kt */ public final class GatewaySocket { private static final long CLIENT_CAPABILITIES = 95; private static final int CLOSE_CODE_CLEAN = 1000; private static final int CLOSE_CODE_DIRTY = 4000; private static final int CLOSE_CODE_UNAUTHORIZED = 4004; private static final boolean COMPRESS_DATA = true; private static final int CONNECTED = 5; private static final int CONNECTING = 2; public static final Companion Companion = new Companion(null); private static final long DEDUPE_USER_OBJECTS = 16; private static final int DISCONNECTED = 0; private static final int DISCOVERING = 1; private static final Set EXPECTED_NULL_DATA_EVENTS = n0.setOf((Object[]) new String[]{"USER_SUBSCRIPTIONS_UPDATE", "USER_PAYMENT_SOURCES_UPDATE"}); private static final String GATEWAY_COMPRESSION = "zlib-stream"; private static final String GATEWAY_ENCODING = "json"; private static final int GATEWAY_URL_RESET_THRESHOLD = 4; private static final int GATEWAY_VERSION = 9; private static final int HEARTBEAT_MAX_RESUME_THRESHOLD = 180000; private static final long HELLO_TIMEOUT = 20000; private static final int IDENTIFYING = 3; private static final int LARGE_GUILD_THRESHOLD = 100; private static final long LAZY_USER_NOTES = 1; private static final long MULTIPLE_GUILD_EXPERIMENT_POPULATIONS = 64; private static final long NO_AFFINE_USER_IDS = 2; private static final int RESUMING = 4; private static final long VERSIONED_READ_STATES = 4; private static final long VERSIONED_USER_GUILD_SETTINGS = 8; private static final Clock clock = ClockFactory.get(); private static final Gson gsonIncludeNulls; private static final Gson gsonOmitNulls; private boolean connected; private boolean connectionReady; private long connectionStartTime; private int connectionState; private final GatewayEventHandler eventHandler; private final Backoff gatewayBackoff; private final GatewayDiscovery gatewayDiscovery; private final GatewaySocketLogger gatewaySocketLogger; private final Function1 gatewayUrlTransform; private boolean hasConnectedOnce; private boolean heartbeatAck; private long heartbeatAckTimeMostRecent; private Timer heartbeatExpeditedTimeout; private long heartbeatInterval; private Timer heartbeater; private Timer helloTimeout; private final Function0 identifyDataProvider; private final Map identifyProperties; private long identifyStartTime; private final Logger logger; private boolean nextReconnectIsImmediate; private int replayedEvents; private final Scheduler scheduler; private int seq; private String sessionId; private final SSLSocketFactory sslSocketFactory; private String token; private final Function1, Unit> trackReadyPayload; private WebSocket webSocket; /* compiled from: GatewaySocket.kt */ /* renamed from: com.discord.gateway.GatewaySocket$1 reason: invalid class name */ public static final class AnonymousClass1 extends o implements Function1 { public final /* synthetic */ GatewaySocket this$0; /* JADX INFO: super call moved to the top of the method (can break code semantics) */ public AnonymousClass1(GatewaySocket gatewaySocket) { super(1); this.this$0 = gatewaySocket; } /* Return type fixed from 'java.lang.Object' to match base method */ /* JADX DEBUG: Method arguments types fixed to match base method, original types: [java.lang.Object] */ @Override // kotlin.jvm.functions.Function1 public /* bridge */ /* synthetic */ Unit invoke(String str) { invoke(str); return Unit.a; } public final void invoke(String str) { m.checkNotNullParameter(str, "message"); Companion.log$default(GatewaySocket.Companion, GatewaySocket.access$getLogger$p(this.this$0), str, false, 2, null); } } /* compiled from: GatewaySocket.kt */ /* renamed from: com.discord.gateway.GatewaySocket$2 reason: invalid class name */ public static final class AnonymousClass2 implements b { public static final AnonymousClass2 INSTANCE = new AnonymousClass2(); public final Boolean call(Boolean bool) { return bool; } } /* compiled from: GatewaySocket.kt */ /* renamed from: com.discord.gateway.GatewaySocket$3 reason: invalid class name */ public static final class AnonymousClass3 implements Action1 { public final /* synthetic */ GatewaySocket this$0; public AnonymousClass3(GatewaySocket gatewaySocket) { this.this$0 = gatewaySocket; } public final void call(Boolean bool) { GatewaySocket gatewaySocket = this.this$0; m.checkNotNullExpressionValue(bool, "isConnected"); GatewaySocket.access$handleDeviceConnectivityChange(gatewaySocket, bool.booleanValue()); } } /* compiled from: GatewaySocket.kt */ /* renamed from: com.discord.gateway.GatewaySocket$4 reason: invalid class name */ public static final class AnonymousClass4 implements Action1 { public final /* synthetic */ GatewaySocket this$0; public AnonymousClass4(GatewaySocket gatewaySocket) { this.this$0 = gatewaySocket; } public final void call(Throwable th) { Logger access$getLogger$p = GatewaySocket.access$getLogger$p(this.this$0); StringBuilder L = a.L("failed to handle connectivity change in "); L.append(this.this$0.getClass().getSimpleName()); Logger.e$default(access$getLogger$p, L.toString(), th, null, 4, null); } } /* compiled from: GatewaySocket.kt */ public static final class Companion { private Companion() { } public /* synthetic */ Companion(DefaultConstructorMarker defaultConstructorMarker) { this(); } public static final /* synthetic */ void access$log(Companion companion, Logger logger, String str, boolean z2) { companion.log(logger, str, z2); } private final long getDelay(long j, Long l) { return (l != null ? l.longValue() : ClockFactory.get().currentTimeMillis()) - j; } public static /* synthetic */ long getDelay$default(Companion companion, long j, Long l, int i, Object obj) { if ((i & 2) != 0) { l = null; } return companion.getDelay(j, l); } private final void log(Logger logger, String str, boolean z2) { Logger.v$default(logger, a.u("[GatewaySocket] ", str), null, 2, null); if (z2) { logger.recordBreadcrumb("Gateway [" + str + ']', "log"); } } public static /* synthetic */ void log$default(Companion companion, Logger logger, String str, boolean z2, int i, Object obj) { if ((i & 2) != 0) { z2 = true; } companion.log(logger, str, z2); } } /* compiled from: GatewaySocket.kt */ public static final class IdentifyData { private final OutgoingPayload.IdentifyClientState clientState; private final String token; public IdentifyData(String str, OutgoingPayload.IdentifyClientState identifyClientState) { m.checkNotNullParameter(str, "token"); this.token = str; this.clientState = identifyClientState; } public final OutgoingPayload.IdentifyClientState getClientState() { return this.clientState; } public final String getToken() { return this.token; } } /* compiled from: GatewaySocket.kt */ public static final class SizeRecordingInputStreamReader extends Reader { private int size; private final InputStreamReader source; public SizeRecordingInputStreamReader(InputStreamReader inputStreamReader, int i) { m.checkNotNullParameter(inputStreamReader, "source"); this.source = inputStreamReader; this.size = i; } /* JADX INFO: this call moved to the top of the method (can break code semantics) */ public /* synthetic */ SizeRecordingInputStreamReader(InputStreamReader inputStreamReader, int i, int i2, DefaultConstructorMarker defaultConstructorMarker) { this(inputStreamReader, (i2 & 2) != 0 ? 0 : i); } @Override // java.io.Reader, java.io.Closeable, java.lang.AutoCloseable public void close() { this.source.close(); } public final int getSize() { return this.size; } public final InputStreamReader getSource() { return this.source; } @Override // java.io.Reader public int read(char[] cArr, int i, int i2) { m.checkNotNullParameter(cArr, "buffer"); int read = this.source.read(cArr, i, i2); if (read != -1) { this.size += read; } return read; } public final void setSize(int i) { this.size = i; } } /* compiled from: GatewaySocket.kt */ public static final class Timer implements Backoff.Scheduler { private final Scheduler scheduler; private Subscription subscription; public Timer(Scheduler scheduler) { m.checkNotNullParameter(scheduler, "scheduler"); this.scheduler = scheduler; } public static final /* synthetic */ Subscription access$getSubscription$p(Timer timer) { return timer.subscription; } public static final /* synthetic */ void access$setSubscription$p(Timer timer, Subscription subscription) { timer.subscription = subscription; } /* JADX DEBUG: Multi-variable search result rejected for r0v0, resolved type: com.discord.gateway.GatewaySocket$Timer */ /* JADX WARN: Multi-variable type inference failed */ public static /* synthetic */ void cancel$default(Timer timer, Function0 function0, int i, Object obj) { if ((i & 1) != 0) { function0 = null; } timer.cancel(function0); } @Override // com.discord.utilities.networking.Backoff.Scheduler public void cancel() { cancel(null); } public final void cancel(Function0 function0) { Subscription subscription = this.subscription; if (subscription != null) { if (subscription != null) { subscription.unsubscribe(); } this.subscription = null; if (function0 != null) { function0.mo1invoke(); } } } public final boolean getPending() { return this.subscription != null; } public final void postInterval(Function0 function0, long j) { m.checkNotNullParameter(function0, "callback"); cancel(); this.subscription = Observable.E(j, j, TimeUnit.MILLISECONDS, j0.p.a.a()).I(this.scheduler).W(new GatewaySocket$Timer$postInterval$1(function0), GatewaySocket$Timer$postInterval$2.INSTANCE); } @Override // com.discord.utilities.networking.Backoff.Scheduler public void schedule(Function0 function0, long j) { m.checkNotNullParameter(function0, "action"); cancel(); this.subscription = Observable.d0(j, TimeUnit.MILLISECONDS).I(this.scheduler).W(new GatewaySocket$Timer$schedule$1(this, function0), GatewaySocket$Timer$schedule$2.INSTANCE); } } public final /* synthetic */ class WhenMappings { public static final /* synthetic */ int[] $EnumSwitchMapping$0; public static final /* synthetic */ int[] $EnumSwitchMapping$1; static { GatewaySocketLogger.LogLevel.values(); int[] iArr = new int[2]; $EnumSwitchMapping$0 = iArr; iArr[GatewaySocketLogger.LogLevel.NONE.ordinal()] = 1; iArr[GatewaySocketLogger.LogLevel.VERBOSE.ordinal()] = 2; Opcode.values(); int[] iArr2 = new int[20]; $EnumSwitchMapping$1 = iArr2; iArr2[Opcode.HELLO.ordinal()] = 1; iArr2[Opcode.RECONNECT.ordinal()] = 2; iArr2[Opcode.INVALID_SESSION.ordinal()] = 3; iArr2[Opcode.HEARTBEAT.ordinal()] = 4; iArr2[Opcode.HEARTBEAT_ACK.ordinal()] = 5; iArr2[Opcode.DISPATCH.ordinal()] = 6; } } static { e eVar = new e(); eVar.g = true; c cVar = c.LOWER_CASE_WITH_UNDERSCORES; eVar.f1382c = cVar; eVar.b(ActivityType.class, new ActivityTypeTypeAdapter()); gsonIncludeNulls = eVar.a(); e eVar2 = new e(); eVar2.f1382c = cVar; gsonOmitNulls = eVar2.a(); } /* JADX DEBUG: Multi-variable search result rejected for r22v0, resolved type: kotlin.jvm.functions.Function1, kotlin.Unit> */ /* JADX DEBUG: Multi-variable search result rejected for r29v0, resolved type: kotlin.jvm.functions.Function1 */ /* JADX WARN: Multi-variable type inference failed */ public GatewaySocket(Function0 function0, Function1, Unit> function1, GatewayEventHandler gatewayEventHandler, Scheduler scheduler, Logger logger, NetworkMonitor networkMonitor, RestConfig restConfig, Context context, Function1 function12, SSLSocketFactory sSLSocketFactory, Map map, GatewaySocketLogger gatewaySocketLogger) { m.checkNotNullParameter(function0, "identifyDataProvider"); m.checkNotNullParameter(function1, "trackReadyPayload"); m.checkNotNullParameter(gatewayEventHandler, "eventHandler"); m.checkNotNullParameter(scheduler, "scheduler"); m.checkNotNullParameter(logger, "logger"); m.checkNotNullParameter(networkMonitor, "networkMonitor"); m.checkNotNullParameter(restConfig, "restConfig"); m.checkNotNullParameter(context, "context"); m.checkNotNullParameter(map, "identifyProperties"); m.checkNotNullParameter(gatewaySocketLogger, "gatewaySocketLogger"); this.identifyDataProvider = function0; this.trackReadyPayload = function1; this.eventHandler = gatewayEventHandler; this.scheduler = scheduler; this.logger = logger; this.gatewayUrlTransform = function12; this.sslSocketFactory = sSLSocketFactory; this.identifyProperties = map; this.gatewaySocketLogger = gatewaySocketLogger; Backoff backoff = new Backoff(1000, 10000, 4, true, new Timer(scheduler)); this.gatewayBackoff = backoff; this.heartbeatExpeditedTimeout = new Timer(scheduler); this.heartbeatInterval = Long.MAX_VALUE; this.heartbeater = new Timer(scheduler); this.heartbeatAck = true; this.helloTimeout = new Timer(scheduler); RestClient restClient = RestClient.INSTANCE; restClient.init(restConfig, context); this.gatewayDiscovery = new GatewayDiscovery(context, scheduler, backoff, new AnonymousClass1(this), restClient.getGateway()); Observable I = networkMonitor.observeIsConnected().I(scheduler); Observable.h0(new r(I.i, new w1(new v1(AnonymousClass2.INSTANCE)))).W(new AnonymousClass3(this), new AnonymousClass4(this)); } /* JADX INFO: this call moved to the top of the method (can break code semantics) */ public /* synthetic */ GatewaySocket(Function0 function0, Function1 function1, GatewayEventHandler gatewayEventHandler, Scheduler scheduler, Logger logger, NetworkMonitor networkMonitor, RestConfig restConfig, Context context, Function1 function12, SSLSocketFactory sSLSocketFactory, Map map, GatewaySocketLogger gatewaySocketLogger, int i, DefaultConstructorMarker defaultConstructorMarker) { this(function0, function1, gatewayEventHandler, scheduler, logger, networkMonitor, restConfig, context, (i & 256) != 0 ? null : function12, (i & 512) != 0 ? null : sSLSocketFactory, (i & 1024) != 0 ? h0.emptyMap() : map, gatewaySocketLogger); } public static final /* synthetic */ void access$cleanup(GatewaySocket gatewaySocket, Function1 function1) { gatewaySocket.cleanup(function1); } public static final /* synthetic */ void access$connect(GatewaySocket gatewaySocket, String str) { gatewaySocket.connect(str); } public static final /* synthetic */ void access$discover(GatewaySocket gatewaySocket) { gatewaySocket.discover(); } public static final /* synthetic */ void access$discoveryFailed(GatewaySocket gatewaySocket) { gatewaySocket.discoveryFailed(); } public static final /* synthetic */ long access$getConnectionStartTime$p(GatewaySocket gatewaySocket) { return gatewaySocket.connectionStartTime; } public static final /* synthetic */ int access$getConnectionState$p(GatewaySocket gatewaySocket) { return gatewaySocket.connectionState; } public static final /* synthetic */ Backoff access$getGatewayBackoff$p(GatewaySocket gatewaySocket) { return gatewaySocket.gatewayBackoff; } public static final /* synthetic */ GatewaySocketLogger access$getGatewaySocketLogger$p(GatewaySocket gatewaySocket) { return gatewaySocket.gatewaySocketLogger; } public static final /* synthetic */ Function1 access$getGatewayUrlTransform$p(GatewaySocket gatewaySocket) { return gatewaySocket.gatewayUrlTransform; } public static final /* synthetic */ Gson access$getGsonOmitNulls$cp() { return gsonOmitNulls; } public static final /* synthetic */ boolean access$getHeartbeatAck$p(GatewaySocket gatewaySocket) { return gatewaySocket.heartbeatAck; } public static final /* synthetic */ Timer access$getHeartbeatExpeditedTimeout$p(GatewaySocket gatewaySocket) { return gatewaySocket.heartbeatExpeditedTimeout; } public static final /* synthetic */ Logger access$getLogger$p(GatewaySocket gatewaySocket) { return gatewaySocket.logger; } public static final /* synthetic */ boolean access$getNextReconnectIsImmediate$p(GatewaySocket gatewaySocket) { return gatewaySocket.nextReconnectIsImmediate; } public static final /* synthetic */ int access$getSeq$p(GatewaySocket gatewaySocket) { return gatewaySocket.seq; } public static final /* synthetic */ WebSocket access$getWebSocket$p(GatewaySocket gatewaySocket) { return gatewaySocket.webSocket; } public static final /* synthetic */ void access$handleClose(GatewaySocket gatewaySocket, boolean z2, int i, String str) { gatewaySocket.handleClose(z2, i, str); } public static final /* synthetic */ void access$handleDeviceConnectivityChange(GatewaySocket gatewaySocket, boolean z2) { gatewaySocket.handleDeviceConnectivityChange(z2); } public static final /* synthetic */ void access$handleHeartbeatTimeout(GatewaySocket gatewaySocket) { gatewaySocket.handleHeartbeatTimeout(); } public static final /* synthetic */ void access$handleWebSocketClose(GatewaySocket gatewaySocket, WebSocket.Closed closed) { gatewaySocket.handleWebSocketClose(closed); } public static final /* synthetic */ void access$handleWebSocketError(GatewaySocket gatewaySocket) { gatewaySocket.handleWebSocketError(); } public static final /* synthetic */ void access$handleWebSocketMessage(GatewaySocket gatewaySocket, InputStreamReader inputStreamReader, int i) { gatewaySocket.handleWebSocketMessage(inputStreamReader, i); } public static final /* synthetic */ void access$handleWebSocketOpened(GatewaySocket gatewaySocket, String str) { gatewaySocket.handleWebSocketOpened(str); } public static final /* synthetic */ void access$heartbeat(GatewaySocket gatewaySocket, int i) { gatewaySocket.heartbeat(i); } public static final /* synthetic */ void access$logError(GatewaySocket gatewaySocket, String str, Exception exc, Map map) { gatewaySocket.logError(str, exc, map); } public static final /* synthetic */ void access$reset(GatewaySocket gatewaySocket, boolean z2, int i, String str) { gatewaySocket.reset(z2, i, str); } public static final /* synthetic */ void access$setConnectionStartTime$p(GatewaySocket gatewaySocket, long j) { gatewaySocket.connectionStartTime = j; } public static final /* synthetic */ void access$setConnectionState$p(GatewaySocket gatewaySocket, int i) { gatewaySocket.connectionState = i; } public static final /* synthetic */ void access$setHeartbeatAck$p(GatewaySocket gatewaySocket, boolean z2) { gatewaySocket.heartbeatAck = z2; } public static final /* synthetic */ void access$setHeartbeatExpeditedTimeout$p(GatewaySocket gatewaySocket, Timer timer) { gatewaySocket.heartbeatExpeditedTimeout = timer; } public static final /* synthetic */ void access$setNextReconnectIsImmediate$p(GatewaySocket gatewaySocket, boolean z2) { gatewaySocket.nextReconnectIsImmediate = z2; } public static final /* synthetic */ void access$setSeq$p(GatewaySocket gatewaySocket, int i) { gatewaySocket.seq = i; } public static final /* synthetic */ void access$setWebSocket$p(GatewaySocket gatewaySocket, WebSocket webSocket) { gatewaySocket.webSocket = webSocket; } private final void cleanup(Function1 function1) { stopHeartbeater(); clearHelloTimeout(); if (function1 != null) { function1.invoke(this.webSocket); } WebSocket webSocket = this.webSocket; if (webSocket != null) { webSocket.resetListeners(); } this.webSocket = null; this.gatewayBackoff.cancel(); } private final void clearHelloTimeout() { this.helloTimeout.cancel(); } public static /* synthetic */ void close$default(GatewaySocket gatewaySocket, boolean z2, int i, Object obj) { if ((i & 1) != 0) { z2 = true; } gatewaySocket.close(z2); } private final void connect(String str) { GatewaySocket$connect$$inlined$apply$lambda$4 gatewaySocket$connect$$inlined$apply$lambda$4; if (this.connectionState == 1) { this.connectionState = 2; Companion.log$default(Companion, this.logger, a.v("Connect to: ", str, ", encoding: json, version 9."), false, 2, null); cleanup(GatewaySocket$connect$2.INSTANCE); this.connectionStartTime = clock.currentTimeMillis(); this.helloTimeout.schedule(new GatewaySocket$connect$3(this), 20000); WebSocket webSocket = new WebSocket(this.scheduler, new GatewaySocket$connect$4(this), this.sslSocketFactory); webSocket.setOnOpened(new GatewaySocket$connect$$inlined$apply$lambda$1(this, str)); webSocket.setOnClosed(new GatewaySocket$connect$$inlined$apply$lambda$2(this, str)); webSocket.setOnMessage(new GatewaySocket$connect$$inlined$apply$lambda$3(this, str)); int ordinal = this.gatewaySocketLogger.getLogLevel().ordinal(); if (ordinal == 0) { gatewaySocket$connect$$inlined$apply$lambda$4 = null; } else if (ordinal == 1) { gatewaySocket$connect$$inlined$apply$lambda$4 = new GatewaySocket$connect$$inlined$apply$lambda$4(this, str); } else { throw new NoWhenBranchMatchedException(); } webSocket.setRawMessageHandler(gatewaySocket$connect$$inlined$apply$lambda$4); webSocket.setOnError(new GatewaySocket$connect$$inlined$apply$lambda$5(this, str)); webSocket.connect(str + "/?encoding=json&v=9&compress=zlib-stream"); this.webSocket = webSocket; } } private final void discover() { this.nextReconnectIsImmediate = false; if (this.connectionState == 1) { this.gatewayDiscovery.discoverGatewayUrl(new GatewaySocket$discover$1(this), new GatewaySocket$discover$2(this)); } } private final void discoveryFailed() { Companion.log$default(Companion, this.logger, a.r("Discovery failed, retrying in ", this.gatewayBackoff.fail(new GatewaySocket$discoveryFailed$delay$1(this)), "ms."), false, 2, null); if (this.gatewayBackoff.hasReachedFailureThreshold()) { reset(false, 0, "Gateway discovery failed."); } } private final void doIdentify() { this.seq = 0; this.sessionId = null; IdentifyData invoke = this.identifyDataProvider.mo1invoke(); if (invoke == null) { handleClose(true, 4004, "No connection info provided."); return; } this.connectionState = 3; this.identifyStartTime = clock.currentTimeMillis(); this.token = invoke.getToken(); Companion.log$default(Companion, this.logger, "Sending identify.", false, 2, null); send$default(this, new Outgoing(Opcode.IDENTIFY, new OutgoingPayload.Identify(invoke.getToken(), 100, true, 95, this.identifyProperties, invoke.getClientState())), false, null, 4, null); } private final void doResume() { this.connectionState = 4; this.replayedEvents = 0; Companion companion = Companion; Logger logger = this.logger; StringBuilder L = a.L("Resuming session "); String str = this.sessionId; if (str == null) { str = ""; } L.append(str); L.append(" at sequence: "); Companion.log$default(companion, logger, a.y(L, this.seq, '.'), false, 2, null); send$default(this, new Outgoing(Opcode.RESUME, new OutgoingPayload.Resume(this.token, this.sessionId, this.seq)), false, null, 4, null); } private final void doResumeOrIdentify() { Companion companion = Companion; long delay$default = Companion.getDelay$default(companion, this.heartbeatAckTimeMostRecent, null, 2, null); float f = this.heartbeatAckTimeMostRecent == 0 ? 0.0f : (((float) delay$default) / 1000.0f) / 60.0f; if (this.sessionId != null && delay$default <= ((long) 180000)) { Logger logger = this.logger; StringBuilder L = a.L("Attempting to resume after elapsed duration of "); String format = String.format("%.2f", Arrays.copyOf(new Object[]{Float.valueOf(f)}, 1)); m.checkNotNullExpressionValue(format, "java.lang.String.format(this, *args)"); L.append(format); L.append(" minutes."); Companion.log$default(companion, logger, L.toString(), false, 2, null); doResume(); } else { handleInvalidSession(false); } this.heartbeatAckTimeMostRecent = clock.currentTimeMillis(); } public static /* synthetic */ void expeditedHeartbeat$default(GatewaySocket gatewaySocket, long j, String str, boolean z2, int i, Object obj) { if ((i & 2) != 0) { str = null; } if ((i & 4) != 0) { z2 = true; } gatewaySocket.expeditedHeartbeat(j, str, z2); } /* JADX DEBUG: Multi-variable search result rejected for r4v7, resolved type: java.lang.Object */ /* JADX WARN: Multi-variable type inference failed */ private final void flattenTraces(Object obj, ArrayList> arrayList) { if (obj != null) { try { if (e0.isMutableList(obj)) { int i = 0; while (true) { int i2 = i + 1; if (i2 < ((List) obj).size()) { Object obj2 = ((List) obj).get(i); Number number = null; if (!(obj2 instanceof String)) { obj2 = null; } String str = (String) obj2; Object obj3 = ((List) obj).get(i2); if (!e0.isMutableMap(obj3)) { obj3 = null; } Map map = (Map) obj3; i += 2; if (!(str == null || map == null)) { if (map.containsKey("micros")) { Object obj4 = map.get("micros"); if (obj4 instanceof Number) { number = obj4; } number = number; } if (number != null) { arrayList.add(new Pair<>(str, Integer.valueOf(number.intValue() / 1000))); } flattenTraces(map.get("calls"), arrayList); } } else { return; } } } } catch (Exception e) { Logger.e$default(this.logger, "Unable to parse ready payload traces", e, null, 4, null); } } } private final String getConnectionPath(ModelPayload.Hello hello) { String joinToString$default; List trace = hello.getTrace(); return (trace == null || (joinToString$default = u.joinToString$default(trace, " -> ", null, null, 0, null, null, 62, null)) == null) ? "???" : joinToString$default; } private final void handleClose(boolean z2, int i, String str) { cleanup(GatewaySocket$handleClose$1.INSTANCE); handleConnected$default(this, null, Boolean.FALSE, 1, null); if (i == 4004) { this.connectionState = 0; reset(z2, i, str); return; } this.connectionState = 1; StringBuilder sb = new StringBuilder(); sb.append("Closed cleanly: "); sb.append(z2); sb.append(", with code: "); sb.append(i); sb.append(", for reason: '"); String D = a.D(sb, str, "'."); if (this.nextReconnectIsImmediate) { Companion.log$default(Companion, this.logger, a.u(D, " Retrying immediately."), false, 2, null); discover(); return; } long fail = this.gatewayBackoff.fail(new GatewaySocket$handleClose$delay$1(this)); Companion companion = Companion; Logger logger = this.logger; Companion.log$default(companion, logger, D + " Retrying in: " + fail + "ms.", false, 2, null); if (this.gatewayBackoff.hasReachedFailureThreshold()) { reset(z2, i, str); } } private final void handleConnected(Boolean bool, Boolean bool2) { if (bool != null) { boolean booleanValue = bool.booleanValue(); this.connected = booleanValue; this.hasConnectedOnce = this.hasConnectedOnce || booleanValue; this.eventHandler.handleConnected(booleanValue); } if (bool2 != null) { boolean booleanValue2 = bool2.booleanValue(); this.connectionReady = booleanValue2; this.eventHandler.handleConnectionReady(booleanValue2); } } public static /* synthetic */ void handleConnected$default(GatewaySocket gatewaySocket, Boolean bool, Boolean bool2, int i, Object obj) { if ((i & 1) != 0) { bool = null; } if ((i & 2) != 0) { bool2 = null; } gatewaySocket.handleConnected(bool, bool2); } private final void handleDeviceConnectivityChange(boolean z2) { if (z2) { expeditedHeartbeat$default(this, 4500, "network detected online", false, 4, null); } else { expeditedHeartbeat$default(this, 9000, "network detected offline", false, 4, null); } } private final void handleDispatch(Object obj, String str, int i, int i2, long j) { if (this.connectionState == 4) { this.replayedEvents++; } if (m.areEqual(str, "READY") || m.areEqual(str, "RESUMED")) { if (str != null) { int hashCode = str.hashCode(); if (hashCode != 77848963) { if (hashCode == 1815529911 && str.equals("RESUMED")) { StringBuilder sb = new StringBuilder(); StringBuilder L = a.L("Resumed session, took "); Companion companion = Companion; L.append(Companion.getDelay$default(companion, this.connectionStartTime, null, 2, null)); L.append("ms, "); sb.append(L.toString()); sb.append("replayed " + this.replayedEvents + " events, new seq: " + this.seq + '.'); String sb2 = sb.toString(); m.checkNotNullExpressionValue(sb2, "StringBuilder()\n … .toString()"); Companion.log$default(companion, this.logger, sb2, false, 2, null); this.replayedEvents = 0; } } else if (str.equals("READY")) { ModelPayload modelPayload = (ModelPayload) obj; if (modelPayload == null) { handleReconnect$default(this, "Reconnect due to invalid ready payload received.", false, 2, null); return; } this.sessionId = modelPayload.getSessionId(); trackReadyPayload(modelPayload, i, i2, j); Companion companion2 = Companion; Logger logger = this.logger; StringBuilder L2 = a.L("Ready with session id: "); L2.append(this.sessionId); L2.append(", took "); Companion.log$default(companion2, logger, a.A(L2, Companion.getDelay$default(companion2, this.connectionStartTime, null, 2, null), "ms"), false, 2, null); } } this.gatewayBackoff.succeed(); this.connectionState = 5; Boolean bool = Boolean.TRUE; handleConnected(bool, bool); } if (obj != null) { this.eventHandler.handleDispatch(str, obj); } else if (u.contains(EXPECTED_NULL_DATA_EVENTS, str)) { this.eventHandler.handleDispatch(str, Unit.a); } else if ((!m.areEqual(str, "READY")) && (!m.areEqual(str, "RESUMED"))) { Logger.w$default(this.logger, a.v("handleDispatch() ", str, " is unhandled!"), null, 2, null); } } private final void handleHeartbeat() { heartbeat(this.seq); } private final void handleHeartbeatAck() { Companion.access$log(Companion, this.logger, "Received heartbeat ACK.", false); this.heartbeatAckTimeMostRecent = clock.currentTimeMillis(); this.heartbeatAck = true; this.heartbeatExpeditedTimeout.cancel(new GatewaySocket$handleHeartbeatAck$1(this)); } private final void handleHeartbeatTimeout() { cleanup(GatewaySocket$handleHeartbeatTimeout$1.INSTANCE); this.connectionState = 1; Companion.log$default(Companion, this.logger, a.r("Ack timeout, reconnecting om ", this.gatewayBackoff.fail(new GatewaySocket$handleHeartbeatTimeout$delay$1(this)), "ms."), false, 2, null); } private final void handleHello(ModelPayload.Hello hello) { clearHelloTimeout(); this.heartbeatInterval = (long) hello.getHeartbeatInterval(); Companion companion = Companion; Logger logger = this.logger; StringBuilder L = a.L("Hello via "); L.append(getConnectionPath(hello)); L.append(", at interval "); L.append(this.heartbeatInterval); L.append(" took "); Companion.log$default(companion, logger, a.A(L, Companion.getDelay$default(companion, this.connectionStartTime, null, 2, null), "ms."), false, 2, null); startHeartbeater(); } private final void handleInvalidSession(boolean z2) { Companion.log$default(Companion, this.logger, a.D(a.L("Invalid session, is "), z2 ? "" : "not", " resumable."), false, 2, null); if (z2) { doResumeOrIdentify(); return; } Boolean bool = Boolean.FALSE; handleConnected(bool, bool); doIdentify(); } private final void handleReconnect(String str, boolean z2) { cleanup(new GatewaySocket$handleReconnect$1(str)); reset(!z2, z2 ? 1000 : 4000, str); handleClose(!z2, 0, str); } public static /* synthetic */ void handleReconnect$default(GatewaySocket gatewaySocket, String str, boolean z2, int i, Object obj) { if ((i & 1) != 0) { str = "Reconnect to gateway requested."; } if ((i & 2) != 0) { z2 = true; } gatewaySocket.handleReconnect(str, z2); } /* JADX WARNING: Code restructure failed: missing block: B:6:0x0010, code lost: if ((r0.length() > 0) != false) goto L_0x0016; */ private final void handleWebSocketClose(WebSocket.Closed closed) { String reason = closed.getReason(); if (reason != null) { } reason = "unspecified reason"; handleClose(true, closed.getCode(), reason); } private final void handleWebSocketError() { handleClose(false, 0, "An error with the web socket occurred."); } private final void handleWebSocketMessage(InputStreamReader inputStreamReader, int i) { long currentTimeMillis = clock.currentTimeMillis(); SizeRecordingInputStreamReader sizeRecordingInputStreamReader = new SizeRecordingInputStreamReader(inputStreamReader, 0, 2, null); Incoming build = ((IncomingParser) new Model.JsonReader(new JsonReader(sizeRecordingInputStreamReader)).parse(new IncomingParser(new GatewaySocket$handleWebSocketMessage$incomingParser$1(this)))).build(); Integer seq = build.getSeq(); Companion companion = Companion; long delay$default = Companion.getDelay$default(companion, currentTimeMillis, null, 2, null); if (seq != null) { this.seq = seq.intValue(); } int ordinal = build.getOpcode().ordinal(); if (ordinal == 1) { handleDispatch(build.getData(), build.getType(), i, sizeRecordingInputStreamReader.getSize(), delay$default); } else if (ordinal == 2) { handleHeartbeat(); } else if (ordinal != 8) { switch (ordinal) { case 10: Object data = build.getData(); Objects.requireNonNull(data, "null cannot be cast to non-null type kotlin.Boolean"); handleInvalidSession(((Boolean) data).booleanValue()); return; case 11: Object data2 = build.getData(); Objects.requireNonNull(data2, "null cannot be cast to non-null type com.discord.models.domain.ModelPayload.Hello"); handleHello((ModelPayload.Hello) data2); return; case 12: handleHeartbeatAck(); return; default: Logger logger = this.logger; StringBuilder L = a.L("Unhandled op code "); L.append(build.getOpcode()); L.append('.'); Companion.log$default(companion, logger, L.toString(), false, 2, null); return; } } else { handleReconnect$default(this, null, false, 1, null); } } private final void handleWebSocketOpened(String str) { Companion companion = Companion; Companion.log$default(companion, this.logger, a.A(a.Q("Connected to ", str, " in "), Companion.getDelay$default(companion, this.connectionStartTime, null, 2, null), "ms."), false, 2, null); doResumeOrIdentify(); } private final void heartbeat(int i) { Companion companion = Companion; Logger logger = this.logger; Companion.access$log(companion, logger, "Sending heartbeat at sequence: " + i + '.', false); send$default(this, new Outgoing(Opcode.HEARTBEAT, Integer.valueOf(i)), false, null, 4, null); } private final void logError(String str, Exception exc, Map map) { Logger logger = this.logger; if (map == null) { map = h0.emptyMap(); } logger.e(str, exc, map); } /* JADX DEBUG: Multi-variable search result rejected for r2v0, resolved type: com.discord.gateway.GatewaySocket */ /* JADX WARN: Multi-variable type inference failed */ public static /* synthetic */ void presenceUpdate$default(GatewaySocket gatewaySocket, ClientStatus clientStatus, Long l, List list, Boolean bool, int i, Object obj) { if ((i & 2) != 0) { l = Long.valueOf(clock.currentTimeMillis()); } if ((i & 4) != 0) { list = null; } if ((i & 8) != 0) { bool = Boolean.FALSE; } gatewaySocket.presenceUpdate(clientStatus, l, list, bool); } /* JADX DEBUG: Multi-variable search result rejected for r1v0, resolved type: com.discord.gateway.GatewaySocket */ /* JADX WARN: Multi-variable type inference failed */ public static /* synthetic */ void requestGuildMembers$default(GatewaySocket gatewaySocket, List list, String str, List list2, Integer num, int i, Object obj) { if ((i & 2) != 0) { str = null; } if ((i & 4) != 0) { list2 = null; } if ((i & 8) != 0) { num = null; } gatewaySocket.requestGuildMembers(list, str, list2, num); } private final void reset(boolean z2, int i, String str) { boolean z3 = false; if (i != 4000) { this.sessionId = null; this.seq = 0; } String str2 = z2 ? "cleanly" : "dirty"; Companion companion = Companion; Logger logger = this.logger; Companion.log$default(companion, logger, "Reset " + str2 + ", with code " + i + ", at sequence " + this.seq + ". Reason: '" + str + "'.", false, 2, null); handleConnected(Boolean.valueOf(i == 4000 && this.connected), Boolean.FALSE); GatewayEventHandler gatewayEventHandler = this.eventHandler; if (i == 4004) { z3 = true; } gatewayEventHandler.handleDisconnect(z3); } private final void schedule(Function0 function0) { new j(function0).X(this.scheduler).W(GatewaySocket$schedule$1.INSTANCE, GatewaySocket$schedule$2.INSTANCE); } private final void send(Outgoing outgoing, boolean z2, Gson gson) { if (!z2 || isSessionEstablished()) { WebSocket webSocket = this.webSocket; if (webSocket == null) { Companion companion = Companion; Logger logger = this.logger; StringBuilder L = a.L("Attempted to send without a web socket that exists, opcode: "); L.append(outgoing.getOp()); L.append('.'); Companion.log$default(companion, logger, L.toString(), false, 2, null); return; } String m = gson.m(outgoing); GatewaySocketLogger gatewaySocketLogger = this.gatewaySocketLogger; m.checkNotNullExpressionValue(m, "json"); gatewaySocketLogger.logOutboundMessage(m); webSocket.message(m); return; } Companion companion2 = Companion; Logger logger2 = this.logger; StringBuilder L2 = a.L("Attempted to send while not being in a connected state, opcode: "); L2.append(outgoing.getOp()); L2.append('.'); Companion.log$default(companion2, logger2, L2.toString(), false, 2, null); } public static /* synthetic */ void send$default(GatewaySocket gatewaySocket, Outgoing outgoing, boolean z2, Gson gson, int i, Object obj) { if ((i & 2) != 0) { z2 = true; } if ((i & 4) != 0) { gson = gsonIncludeNulls; m.checkNotNullExpressionValue(gson, "gsonIncludeNulls"); } gatewaySocket.send(outgoing, z2, gson); } private final void startHeartbeater() { this.heartbeater.cancel(); this.heartbeatAck = true; this.heartbeater.postInterval(new GatewaySocket$startHeartbeater$1(this), this.heartbeatInterval); } private final void stopHeartbeater() { this.heartbeater.cancel(); this.heartbeatExpeditedTimeout.cancel(); } /* JADX WARNING: Code restructure failed: missing block: B:14:0x0073, code lost: if (d0.g0.t.startsWith$default(r6.component1(), "gateway-", false, 2, null) != false) goto L_0x0077; */ private final void trackReadyPayload(ModelPayload modelPayload, int i, int i2, long j) { int i3; int size = modelPayload.getGuilds().size(); int i4 = 0; int i5 = 0; for (Guild guild : modelPayload.getGuilds()) { List g = guild.g(); if (g != null) { for (Channel channel : g) { i4++; if (channel.A() == 4) { i5++; } } } } ArrayList> arrayList = new ArrayList<>(); flattenTraces(modelPayload.getTrace(), arrayList); if (arrayList.size() > 0) { Pair pair = arrayList.get(0); i3 = pair.component2().intValue(); } i3 = 0; Iterator> it = arrayList.iterator(); int i6 = 0; int i7 = 0; while (it.hasNext()) { Pair next = it.next(); String component1 = next.component1(); int intValue = next.component2().intValue(); if (m.areEqual(component1, "start_session")) { i6 = intValue; } else if (m.areEqual(component1, "guilds_connect")) { i7 = intValue; } } Function1, Unit> function1 = this.trackReadyPayload; Companion companion = Companion; function1.invoke(h0.mapOf(d0.o.to("duration_ms_since_connection_start", Long.valueOf(Companion.getDelay$default(companion, this.connectionStartTime, null, 2, null))), d0.o.to("duration_ms_since_identify_start", Long.valueOf(Companion.getDelay$default(companion, this.identifyStartTime, null, 2, null))), d0.o.to("identify_total_server_duration_ms", Integer.valueOf(i3)), d0.o.to("identify_api_duration_ms", Integer.valueOf(i6)), d0.o.to("identify_guilds_duration_ms", Integer.valueOf(i7)), d0.o.to("compressed_byte_size", Integer.valueOf(i)), d0.o.to("uncompressed_byte_size", Integer.valueOf(i2)), d0.o.to("compression_algorithm", "zlib"), d0.o.to("packing_algorithm", "json"), d0.o.to("unpack_duration_ms", Long.valueOf(j)), d0.o.to("is_reconnect", Boolean.valueOf(this.hasConnectedOnce)), d0.o.to("is_fast_connect", Boolean.FALSE), d0.o.to("num_guilds", Integer.valueOf(size)), d0.o.to("num_guild_channels", Integer.valueOf(i4)), d0.o.to("num_guild_category_channels", Integer.valueOf(i5)))); } public final void callConnect(long j) { schedule(new GatewaySocket$callConnect$1(this, j)); } public final void close(boolean z2) { schedule(new GatewaySocket$close$1(this, z2)); } public final void connect() { schedule(new GatewaySocket$connect$1(this)); } public final void expeditedHeartbeat(long j, String str, boolean z2) { schedule(new GatewaySocket$expeditedHeartbeat$1(this, str, j, z2)); } public final boolean isSessionEstablished() { return this.connectionState == 5; } public final void presenceUpdate(ClientStatus clientStatus, Long l, List list, Boolean bool) { schedule(new GatewaySocket$presenceUpdate$1(this, clientStatus, list, l, bool)); } public final void requestApplicationCommands(OutgoingPayload.ApplicationCommandRequest applicationCommandRequest) { m.checkNotNullParameter(applicationCommandRequest, "request"); Outgoing outgoing = new Outgoing(Opcode.REQUEST_GUILD_APPLICATION_COMMANDS, applicationCommandRequest); Gson gson = gsonOmitNulls; m.checkNotNullExpressionValue(gson, "gsonOmitNulls"); send$default(this, outgoing, false, gson, 2, null); } public final void requestGuildMembers(List list) { requestGuildMembers$default(this, list, null, null, null, 14, null); } public final void requestGuildMembers(List list, String str) { requestGuildMembers$default(this, list, str, null, null, 12, null); } public final void requestGuildMembers(List list, String str, List list2) { requestGuildMembers$default(this, list, str, list2, null, 8, null); } public final void requestGuildMembers(List list, String str, List list2, Integer num) { m.checkNotNullParameter(list, "guildIds"); schedule(new GatewaySocket$requestGuildMembers$1(this, list, str, list2, num)); } public final void resetOnError() { schedule(new GatewaySocket$resetOnError$1(this)); } public final void simulateReconnectForTesting() { schedule(new GatewaySocket$simulateReconnectForTesting$1(this)); } public final void streamCreate(String str, long j, Long l, String str2) { m.checkNotNullParameter(str, "streamType"); Companion companion = Companion; Logger logger = this.logger; Companion.log$default(companion, logger, "Sending STREAM_CREATE: " + j + ' ' + l, false, 2, null); send$default(this, new Outgoing(Opcode.STREAM_CREATE, new OutgoingPayload.CreateStream(str, j, l, str2)), false, null, 6, null); } public final void streamDelete(String str) { m.checkNotNullParameter(str, "streamKey"); schedule(new GatewaySocket$streamDelete$1(this, str)); } public final void streamPing(String str) { m.checkNotNullParameter(str, "streamKey"); schedule(new GatewaySocket$streamPing$1(this, str)); } public final void streamWatch(String str) { m.checkNotNullParameter(str, "streamKey"); schedule(new GatewaySocket$streamWatch$1(this, str)); } public final void updateGuildSubscriptions(long j, OutgoingPayload.GuildSubscriptions guildSubscriptions) { m.checkNotNullParameter(guildSubscriptions, "guildSubscriptions"); Companion companion = Companion; Logger logger = this.logger; Companion.log$default(companion, logger, "sending guild subscriptions: " + j + " -- " + guildSubscriptions, false, 2, null); Opcode opcode = Opcode.GUILD_SUBSCRIPTIONS; Boolean typing = guildSubscriptions.getTyping(); Boolean activities = guildSubscriptions.getActivities(); List members = guildSubscriptions.getMembers(); Outgoing outgoing = new Outgoing(opcode, new OutgoingPayload.GuildSubscriptionsUpdate(j, typing, activities, members != null ? u.toList(members) : null, guildSubscriptions.getChannels(), guildSubscriptions.getThreads(), guildSubscriptions.getThreadMemberLists())); Gson gson = gsonOmitNulls; m.checkNotNullExpressionValue(gson, "gsonOmitNulls"); send$default(this, outgoing, false, gson, 2, null); } public final void voiceServerPing() { schedule(new GatewaySocket$voiceServerPing$1(this)); } public final void voiceStateUpdate(Long l, Long l2, boolean z2, boolean z3, boolean z4, String str, boolean z5) { schedule(new GatewaySocket$voiceStateUpdate$1(this, l, l2, z2, z3, str, z5, z4)); } }