package com.ea.nimble; import android.support.v4.media.session.PlaybackStateCompat; import android.text.TextUtils; import com.ea.nimble.Error; import com.ea.nimble.IHttpRequest; import com.ea.nimble.Log; import com.ea.nimble.Network; import com.google.firebase.perf.network.FirebasePerfUrlConnection; import com.ironsource.nb; import com.unity3d.ads.core.domain.InitializeAndroidBoldSDK; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URLConnection; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; /* loaded from: classes2.dex */ class NetworkConnection implements NetworkConnectionHandle, Runnable, LogSource { private static final int MAXIMUM_RAW_DATA_LENGTH = 1048576; static int s_loggingIdCount = 100; private NetworkConnectionCallback m_completionCallback; private Date m_connectionStartTimestamp; private NetworkConnectionCallback m_headerCallback; private final String m_loggingId; private final NetworkImpl m_manager; private IOperationalTelemetryDispatch m_otDispatch; private NetworkConnectionCallback m_progressCallback; private final HttpRequest m_request; private String m_requestDataForLog; private final HttpResponse m_response; private StringBuilder m_responseDataForLog; private Thread m_thread; public String getLogSourceTitle() { return InitializeAndroidBoldSDK.MSG_NETWORK; } public NetworkConnection(NetworkImpl networkImpl, HttpRequest httpRequest) { this(networkImpl, httpRequest, null); } public NetworkConnection(NetworkImpl networkImpl, HttpRequest httpRequest, IOperationalTelemetryDispatch iOperationalTelemetryDispatch) { this.m_manager = networkImpl; this.m_thread = null; this.m_request = httpRequest; this.m_response = new HttpResponse(); this.m_headerCallback = null; this.m_progressCallback = null; this.m_completionCallback = null; this.m_connectionStartTimestamp = null; this.m_otDispatch = iOperationalTelemetryDispatch; this.m_loggingId = String.valueOf(s_loggingIdCount); int i = s_loggingIdCount; s_loggingIdCount = i + 1; if (i >= 1000) { s_loggingIdCount = 100; } } @Override // com.ea.nimble.NetworkConnectionHandle public HttpRequest getRequest() { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); return this.m_request; } @Override // com.ea.nimble.NetworkConnectionHandle public HttpResponse getResponse() { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); return this.m_response; } @Override // com.ea.nimble.NetworkConnectionHandle public NetworkConnectionCallback getHeaderCallback() { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); return this.m_headerCallback; } @Override // com.ea.nimble.NetworkConnectionHandle public void setHeaderCallback(NetworkConnectionCallback networkConnectionCallback) { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); this.m_headerCallback = networkConnectionCallback; } @Override // com.ea.nimble.NetworkConnectionHandle public NetworkConnectionCallback getProgressCallback() { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); return this.m_progressCallback; } @Override // com.ea.nimble.NetworkConnectionHandle public void setProgressCallback(NetworkConnectionCallback networkConnectionCallback) { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); this.m_progressCallback = networkConnectionCallback; } @Override // com.ea.nimble.NetworkConnectionHandle public NetworkConnectionCallback getCompletionCallback() { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); return this.m_completionCallback; } @Override // com.ea.nimble.NetworkConnectionHandle public void setCompletionCallback(NetworkConnectionCallback networkConnectionCallback) { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); this.m_completionCallback = networkConnectionCallback; } @Override // com.ea.nimble.NetworkConnectionHandle public void waitOn() { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); synchronized (this) { while (!this.m_response.isCompleted) { try { wait(); } catch (InterruptedException unused) { } } } } @Override // com.ea.nimble.NetworkConnectionHandle public void cancel() { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); synchronized (this) { try { Thread thread = this.m_thread; if (thread != null) { thread.interrupt(); } else { finishWithError(new Error(Error.Code.NETWORK_OPERATION_CANCELLED, "Network connection " + this + " is cancelled")); } } catch (Throwable th) { throw th; } } } public void cancelForAppSuspend() { cancel(); } public void run() { Log.Helper.LOGPUBLICFUNCS("NetworkConnection"); try { try { try { try { if (this.m_response.isCompleted) { synchronized (this) { this.m_thread = null; } return; } if (Thread.interrupted()) { throw new InterruptedIOException(); } synchronized (this) { this.m_thread = Thread.currentThread(); } HttpURLConnection httpURLConnection = (HttpURLConnection) ((URLConnection) FirebasePerfUrlConnection.instrument(this.m_request.getUrl().openConnection())); httpURLConnection.setRequestMethod(this.m_request.method.toString()); httpURLConnection.setConnectTimeout((int) (this.m_request.timeout * 1000.0d)); httpURLConnection.setReadTimeout((int) (this.m_request.timeout * 1000.0d)); httpURLConnection.setRequestProperty(HTTP.CONN_DIRECTIVE, "close"); this.m_requestDataForLog = null; this.m_responseDataForLog = null; if (Thread.interrupted()) { throw new InterruptedIOException(); } httpSend(httpURLConnection); if (Thread.interrupted()) { throw new InterruptedIOException(); } httpRecv(httpURLConnection); finish(); synchronized (this) { this.m_thread = null; } } catch (InterruptedIOException e) { finishWithError(new Error(Error.Code.NETWORK_OPERATION_CANCELLED, "Connection " + this + " is cancelled", e)); synchronized (this) { this.m_thread = null; } } catch (ClassCastException e2) { finishWithError(new Error(Error.Code.NETWORK_UNSUPPORTED_CONNECTION_TYPE, "Request " + this + " failed for unsupported connection type" + this.m_request.getUrl().getProtocol(), e2)); synchronized (this) { this.m_thread = null; } } } catch (SocketTimeoutException e3) { finishWithError(new Error(Error.Code.NETWORK_TIMEOUT, "Connection " + this + " timed out", e3)); synchronized (this) { this.m_thread = null; } } catch (IOException e4) { finishWithError(new Error(Error.Code.NETWORK_CONNECTION_ERROR, "Connection " + this + " failed with I/O exception", e4)); synchronized (this) { this.m_thread = null; } } } catch (Error e5) { finishWithError(e5); synchronized (this) { this.m_thread = null; } } catch (UnknownHostException e6) { Network.Status status = this.m_manager.getStatus(); if (status != Network.Status.OK) { finishWithError(new Error(Error.Code.NETWORK_NO_CONNECTION, "No network connection, network status " + status.toString(), e6)); } else { finishWithError(new Error(Error.Code.NETWORK_UNREACHABLE, "Request " + this + " failed for unreachable host", e6)); } synchronized (this) { this.m_thread = null; } } catch (Exception e7) { finishWithError(new Error(Error.Code.SYSTEM_UNEXPECTED, "Unexpected error.", e7)); synchronized (this) { this.m_thread = null; } } } catch (Throwable th) { synchronized (this) { this.m_thread = null; throw th; } } } private void httpSend(HttpURLConnection httpURLConnection) throws IOException { Log.Helper.LOGFUNCS("NetworkConnection"); this.m_connectionStartTimestamp = new Date(); HashMap hashMap = this.m_request.headers; if (hashMap != null) { for (String str : hashMap.keySet()) { httpURLConnection.setRequestProperty(str, this.m_request.headers.get(str)); } } logRequest(); byte[] byteArray = this.m_request.data.toByteArray(); if (byteArray == null || byteArray.length <= 0) { return; } httpURLConnection.setDoOutput(true); httpURLConnection.setFixedLengthStreamingMode(byteArray.length); OutputStream outputStream = null; try { try { outputStream = httpURLConnection.getOutputStream(); outputStream.write(byteArray); } catch (Exception e) { StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); Log.Helper.LOGE(this, "Exception in network connection:" + stringWriter.toString(), new Object[0]); if (outputStream == null) { return; } } outputStream.close(); } catch (Throwable th) { if (outputStream != null) { outputStream.close(); } throw th; } } private void httpRecv(HttpURLConnection httpURLConnection) throws IOException, Error { InputStream errorStream; boolean z; Log.Helper.LOGFUNCS("NetworkConnection"); try { try { errorStream = httpURLConnection.getInputStream(); z = false; } catch (Exception unused) { errorStream = httpURLConnection.getErrorStream(); z = true; } try { this.m_response.url = httpURLConnection.getURL(); this.m_response.statusCode = httpURLConnection.getResponseCode(); this.m_response.expectedContentLength = httpURLConnection.getContentLength(); this.m_response.lastModified = httpURLConnection.getLastModified(); for (Map.Entry> entry : httpURLConnection.getHeaderFields().entrySet()) { this.m_response.headers.put(entry.getKey(), TextUtils.join(", ", entry.getValue())); } boolean z2 = this.m_response.expectedContentLength > PlaybackStateCompat.ACTION_SET_CAPTIONING_ENABLED; boolean validString = Utility.validString(this.m_request.targetFilePath); boolean z3 = this.m_request.getMethod() == IHttpRequest.Method.HEAD; HttpResponse httpResponse = this.m_response; int i = httpResponse.statusCode; boolean z4 = i == 200 || i == 206; boolean z5 = (z || errorStream == null || !z4) ? false : true; if (z2 && !z3) { if (!validString) { throw new Error(Error.Code.NETWORK_OVERSIZE_DATA, "Request " + this + " is oversize, please provide a local file path to download it as file."); } if (!z5) { throw new Error(Error.Code.NETWORK_OVERSIZE_DATA, "HTTP error for file download with an oversized error response."); } } httpResponse.downloadedContentLength = 0L; NetworkConnectionCallback networkConnectionCallback = this.m_headerCallback; if (networkConnectionCallback != null) { networkConnectionCallback.callback(this); } if (!z3) { if (validString && z5) { downloadToFile(errorStream); errorStream = null; } else { HttpResponse httpResponse2 = this.m_response; long j = httpResponse2.expectedContentLength; if (j != 0) { ByteBufferIOStream byteBufferIOStream = httpResponse2.data; if (byteBufferIOStream == null) { httpResponse2.data = new ByteBufferIOStream((int) j); } else { byteBufferIOStream.clear(); } if (errorStream != null) { downloadToBuffer(errorStream); errorStream = null; } else { throw new Error(Error.Code.SYSTEM_UNEXPECTED, "Request " + this + " failed because no stream available to read expected response data."); } } if (!z4) { if (z) { throw new HttpError(this.m_response.statusCode, "Request " + this + " failed for HTTP error."); } throw new HttpError(this.m_response.statusCode, "Request " + this + " failed for HTTP error even the response data is from normal response stream."); } if (z) { throw new Error(Error.Code.SYSTEM_UNEXPECTED, "Request " + this + " failed because response is from error stream even the status code(" + this.m_response.statusCode + "). In some cases, you may ignore this and treat it as success."); } } } } finally { if (errorStream != null) { errorStream.close(); } logCommunication(); } } catch (Exception e) { throw new Error(Error.Code.NETWORK_CONNECTION_ERROR, "Fail to get either input stream or error stream from HTTP connection.", e); } } /* JADX WARN: Removed duplicated region for block: B:68:0x01a3 */ /* JADX WARN: Removed duplicated region for block: B:70:0x01a8 */ /* Code decompiled incorrectly, please refer to instructions dump. To view partially-correct add '--show-bad-code' argument */ private void downloadToFile(java.io.InputStream r15) throws java.io.IOException { /* Method dump skipped, instructions count: 468 To view this dump add '--comments-level debug' option */ throw new UnsupportedOperationException("Method not decompiled: com.ea.nimble.NetworkConnection.downloadToFile(java.io.InputStream):void"); } private void downloadToBuffer(InputStream inputStream) throws IOException { int read; Log.Helper.LOGFUNCS("NetworkConnection"); prepareResponseLog(); while (true) { try { byte[] prepareSegment = this.m_response.data.prepareSegment(); int i = 0; if (prepareSegment == null) { Log.Helper.LOGE(this, "Error preparing segment", new Object[0]); break; } do { read = inputStream.read(prepareSegment, i, prepareSegment.length - i); if (!Thread.interrupted()) { if (read < 0) { break; } if (read == 0) { Thread.yield(); } else { prepareResponseLog(prepareSegment, i, read); i += read; this.m_response.downloadedContentLength += read; } } else { throw new InterruptedIOException(); } } while (i < prepareSegment.length); this.m_response.data.appendSegmentToBuffer(prepareSegment, i); NetworkConnectionCallback networkConnectionCallback = this.m_progressCallback; if (networkConnectionCallback != null) { networkConnectionCallback.callback(this); } if (read < 0) { break; } } catch (Throwable th) { inputStream.close(); throw th; } } inputStream.close(); } private void finish() { Log.Helper.LOGFUNCS("NetworkConnection"); this.m_response.isCompleted = true; logOperationalTelemetryResponse(); NetworkConnectionCallback networkConnectionCallback = this.m_completionCallback; if (networkConnectionCallback != null) { networkConnectionCallback.callback(this); } synchronized (this) { notifyAll(); } this.m_manager.removeConnection(this); } public void finishWithError(Exception exc) { Log.Helper.LOGFUNCS("NetworkConnection"); if (this.m_response.isCompleted) { Log.Helper.LOGI(this, "Finished connection %s skipped an error %s", toString(), exc.toString()); return; } Log.Helper.LOGW(this, "Running connection number %s with name %s failed for error %s", this.m_loggingId, toString(), exc.toString()); this.m_response.error = exc; finish(); } private String prepareRequestLog() { String str; Log.Helper.LOGFUNCS("NetworkConnection"); ByteArrayOutputStream byteArrayOutputStream = this.m_request.data; int i = 2048; if (byteArrayOutputStream != null && byteArrayOutputStream.size() > 0) { i = 2048 + this.m_request.data.size(); try { str = this.m_request.data.toString("UTF-8"); } catch (UnsupportedEncodingException unused) { str = "<-- UNREADABLE -->"; } } else { str = (this.m_request.getMethod() == IHttpRequest.Method.POST || this.m_request.getMethod() == IHttpRequest.Method.PUT) ? "<-- EMPTY -->" : null; } StringBuilder sb = new StringBuilder(i); sb.append("REQUEST: "); sb.append(this.m_request.method.toString()); sb.append(' '); sb.append(this.m_request.url.toString()); sb.append('\n'); generateHttpHeaderAndBodyLogString(sb, false, this.m_request.headers, str); return sb.toString(); } private void prepareResponseLog() { Log.Helper.LOGFUNCS("NetworkConnection"); if (Log.getComponent().getThresholdLevel() > 100) { return; } long j = this.m_response.expectedContentLength; this.m_responseDataForLog = new StringBuilder(j > 0 ? (int) j : 4096); } private void prepareResponseLog(byte[] bArr, int i, int i2) { Log.Helper.LOGFUNCS("NetworkConnection"); if (Log.getComponent().getThresholdLevel() > 100 || this.m_responseDataForLog == null) { return; } this.m_responseDataForLog.append(new String(bArr, i, i2, StandardCharsets.UTF_8)); } private String multiplyStringNTimes(String str, int i) { Log.Helper.LOGFUNCS("NetworkConnection"); StringBuilder sb = new StringBuilder(str.length() * i); for (int i2 = 0; i2 < i; i2++) { sb.append(str); } return sb.toString(); } private String beautifyJSONString(String str) { String jSONArray; Log.Helper.LOGFUNCS("NetworkConnection"); if (str == null) { return str; } try { Object nextValue = new JSONTokener(str).nextValue(); if (nextValue instanceof JSONObject) { jSONArray = ((JSONObject) nextValue).toString(4); } else { jSONArray = nextValue instanceof JSONArray ? ((JSONArray) nextValue).toString(4) : null; } return jSONArray != null ? jSONArray : str; } catch (JSONException unused) { return str; } } private void logRequest() { Log.Helper.LOGFUNCS("NetworkConnection"); if (Log.getComponent().getThresholdLevel() > 100) { return; } String prepareRequestLog = prepareRequestLog(); this.m_requestDataForLog = prepareRequestLog; Log.Helper.LOGD(this, "\n>>>> CONNECTION ID %s BEGIN >>>>>>>>>>>>>>>>>>\n%s<<<< CONNECTION BEGIN <<<<<<<<<<<<<<<<<<<<<<<<<\n", this.m_loggingId, prepareRequestLog); } private void logCommunication() { String str; Log.Helper.LOGFUNCS("NetworkConnection"); if (Log.getComponent().getThresholdLevel() > 100) { return; } if (this.m_requestDataForLog == null) { this.m_requestDataForLog = prepareRequestLog(); } int length = 4096 + this.m_requestDataForLog.length(); boolean z = this.m_request.targetFilePath != null; StringBuilder sb = this.m_responseDataForLog; if (sb == null || sb.length() <= 0) { str = z ? "<-- FILE -->" : "<-- EMPTY -->"; } else { try { str = this.m_responseDataForLog.toString(); } catch (Exception unused) { str = "<-- UNREADABLE -->"; } } StringBuilder sb2 = new StringBuilder(length + str.length()); sb2.append(String.format("%n>>>> CONNECTION ID %s FINISH >>>> REQUEST >>>>%n", this.m_loggingId)); sb2.append(this.m_requestDataForLog); sb2.append("<<<< REQUEST <<<<<<<< -- >>>>>>>> RESPONSE >>>>\n"); sb2.append("RESP URL: "); sb2.append(this.m_response.url.toString()); sb2.append('\n'); sb2.append("RESP STATUS: "); sb2.append(this.m_response.statusCode); sb2.append('\n'); if (this.m_response.getError() != null) { sb2.append("RESP ERROR: "); if (this.m_response.getError().getMessage() != null) { sb2.append(this.m_response.getError().getMessage()); sb2.append("\n"); } else { sb2.append("<-- UNKNOWN -->\n"); } } if (z) { sb2.append("RESP FILE: "); sb2.append(this.m_request.targetFilePath); sb2.append("\n"); } generateHttpHeaderAndBodyLogString(sb2, true, this.m_response.headers, str); sb2.append("<<<< RESPONSE <<<< CONNECTION FINISH <<<<<<<<<<"); Log.Helper.LOGD(this, sb2.toString(), new Object[0]); } private void generateHttpHeaderAndBodyLogString(StringBuilder sb, boolean z, Map map, String str) { Log.Helper.LOGFUNCS("NetworkConnection"); String str2 = z ? "RESP" : "REQ"; boolean z2 = false; if (map != null && map.size() > 0) { boolean z3 = false; for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); if (key != null || z) { if (key == null) { key = "(null)"; } sb.append(str2); sb.append(" HEADER: "); sb.append(key); String value = entry.getValue(); String str3 = value != null ? value : "(null)"; sb.append(" VALUE: "); sb.append(str3); sb.append('\n'); if (key.equals("Content-Type") && (str3.contains(nb.L) || str3.contains("text/json"))) { z3 = true; } } else { String str4 = map.get(key); Log.Helper.LOGW("Network request contains a null key with value %s", str4 != null ? str4 : "(null)", new Object[0]); } } z2 = z3; } if (str != null) { sb.append(str2); sb.append(" BODY:\n"); if (z2) { str = beautifyJSONString(str); } sb.append(str); sb.append('\n'); } } /* JADX WARN: Can't wrap try/catch for region: R(12:14|(2:16|(2:18|19))|20|(1:22)(1:55)|23|(2:25|(12:27|28|29|30|31|(1:45)(1:35)|36|37|38|39|40|41)(3:48|49|50))(1:54)|51|37|38|39|40|41) */ /* JADX WARN: Code restructure failed: missing block: B:44:0x0145, code lost: com.ea.nimble.Log.Helper.LOGE(r17, "Failed to add " + r13 + " to eventDict.", new java.lang.Object[0]); */ /* JADX WARN: Unreachable blocks removed: 1, instructions: 1 */ /* Code decompiled incorrectly, please refer to instructions dump. To view partially-correct add '--show-bad-code' argument */ public void logOperationalTelemetryResponse() { /* Method dump skipped, instructions count: 369 To view this dump add '--comments-level debug' option */ throw new UnsupportedOperationException("Method not decompiled: com.ea.nimble.NetworkConnection.logOperationalTelemetryResponse():void"); } }