package com.onesignal;

import android.net.TrafficStats;
import android.os.Build;
import androidx.browser.trusted.sharing.ShareTarget;
import com.onesignal.OSThrowable;
import com.onesignal.OneSignal;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONObject;

/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class OneSignalRestClient {
    private static final String BASE_URL = "https://api.onesignal.com/";
    static final String CACHE_KEY_GET_TAGS = "CACHE_KEY_GET_TAGS";
    static final String CACHE_KEY_REMOTE_PARAMS = "CACHE_KEY_REMOTE_PARAMS";
    private static final int GET_TIMEOUT = 60000;
    private static final String OS_ACCEPT_HEADER = "application/vnd.onesignal.v1+json";
    private static final String OS_API_VERSION = "1";
    private static final int THREAD_ID = 10000;
    private static final int TIMEOUT = 120000;

    /* JADX INFO: Access modifiers changed from: package-private */
    /* loaded from: classes.dex */
    public static abstract class ResponseHandler {
        void onFailure(int i, String str, Throwable th) {
        }

        void onSuccess(String str) {
        }
    }

    private static int getThreadTimeout(int i) {
        return i + 5000;
    }

    OneSignalRestClient() {
    }

    public static void put(final String str, final JSONObject jSONObject, final ResponseHandler responseHandler) {
        new Thread(new Runnable() { // from class: com.onesignal.OneSignalRestClient.1
            @Override // java.lang.Runnable
            public void run() {
                OneSignalRestClient.makeRequest(str, "PUT", jSONObject, responseHandler, OneSignalRestClient.TIMEOUT, null);
            }
        }, "OS_REST_ASYNC_PUT").start();
    }

    public static void post(final String str, final JSONObject jSONObject, final ResponseHandler responseHandler) {
        new Thread(new Runnable() { // from class: com.onesignal.OneSignalRestClient.2
            @Override // java.lang.Runnable
            public void run() {
                OneSignalRestClient.makeRequest(str, ShareTarget.METHOD_POST, jSONObject, responseHandler, OneSignalRestClient.TIMEOUT, null);
            }
        }, "OS_REST_ASYNC_POST").start();
    }

    public static void get(final String str, final ResponseHandler responseHandler, final String str2) {
        new Thread(new Runnable() { // from class: com.onesignal.OneSignalRestClient.3
            @Override // java.lang.Runnable
            public void run() {
                OneSignalRestClient.makeRequest(str, null, null, responseHandler, OneSignalRestClient.GET_TIMEOUT, str2);
            }
        }, "OS_REST_ASYNC_GET").start();
    }

    public static void getSync(String str, ResponseHandler responseHandler, String str2) {
        makeRequest(str, null, null, responseHandler, GET_TIMEOUT, str2);
    }

    public static void putSync(String str, JSONObject jSONObject, ResponseHandler responseHandler) {
        makeRequest(str, "PUT", jSONObject, responseHandler, TIMEOUT, null);
    }

    public static void postSync(String str, JSONObject jSONObject, ResponseHandler responseHandler) {
        makeRequest(str, ShareTarget.METHOD_POST, jSONObject, responseHandler, TIMEOUT, null);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void makeRequest(final String str, final String str2, final JSONObject jSONObject, final ResponseHandler responseHandler, final int i, final String str3) {
        if (OSUtils.isRunningOnMainThread()) {
            throw new OSThrowable.OSMainThreadException("Method: " + str2 + " was called from the Main Thread!");
        }
        if (str2 == null || !OneSignal.shouldLogUserPrivacyConsentErrorMessageForMethodName(null)) {
            final Thread[] threadArr = new Thread[1];
            Thread thread = new Thread(new Runnable() { // from class: com.onesignal.OneSignalRestClient.4
                @Override // java.lang.Runnable
                public void run() {
                    threadArr[0] = OneSignalRestClient.startHTTPConnection(str, str2, jSONObject, responseHandler, i, str3);
                }
            }, "OS_HTTPConnection");
            thread.start();
            try {
                thread.join(getThreadTimeout(i));
                if (thread.getState() != Thread.State.TERMINATED) {
                    thread.interrupt();
                }
                if (threadArr[0] != null) {
                    threadArr[0].join();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* JADX WARN: Code restructure failed: missing block: B:46:0x02d7, code lost:
    
        return r0;
     */
    /* JADX WARN: Code restructure failed: missing block: B:81:0x02d4, code lost:
    
        if (r8 != null) goto L65;
     */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public static Thread startHTTPConnection(String str, String str2, JSONObject jSONObject, ResponseHandler responseHandler, int i, String str3) {
        HttpURLConnection httpURLConnection;
        Thread callResponseHandlerOnFailure;
        String headerField;
        if (Build.VERSION.SDK_INT >= 26) {
            TrafficStats.setThreadStatsTag(THREAD_ID);
        }
        int i2 = -1;
        try {
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "OneSignalRestClient: Making request to: https://api.onesignal.com/" + str);
            httpURLConnection = newHttpURLConnection(str);
            try {
                if (Build.VERSION.SDK_INT < 22 && (httpURLConnection instanceof HttpsURLConnection)) {
                    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
                    httpsURLConnection.setSSLSocketFactory(new TLS12SocketFactory(httpsURLConnection.getSSLSocketFactory()));
                }
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setConnectTimeout(i);
                httpURLConnection.setReadTimeout(i);
                httpURLConnection.setRequestProperty("SDK-Version", "onesignal/android/" + OneSignal.getSdkVersionRaw());
                httpURLConnection.setRequestProperty("Accept", OS_ACCEPT_HEADER);
                if (jSONObject != null) {
                    httpURLConnection.setDoInput(true);
                }
                if (str2 != null) {
                    httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    httpURLConnection.setRequestMethod(str2);
                    httpURLConnection.setDoOutput(true);
                }
                if (jSONObject != null) {
                    String unescapedEUIDString = JSONUtils.toUnescapedEUIDString(jSONObject);
                    OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "OneSignalRestClient: " + str2 + " SEND JSON: " + unescapedEUIDString);
                    byte[] bytes = unescapedEUIDString.getBytes("UTF-8");
                    httpURLConnection.setFixedLengthStreamingMode(bytes.length);
                    httpURLConnection.getOutputStream().write(bytes);
                }
                if (str3 != null) {
                    String string = OneSignalPrefs.getString(OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_ETAG_PREFIX + str3, null);
                    if (string != null) {
                        httpURLConnection.setRequestProperty("if-none-match", string);
                        OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "OneSignalRestClient: Adding header if-none-match: " + string);
                    }
                }
                i2 = httpURLConnection.getResponseCode();
                try {
                    OneSignal.Log(OneSignal.LOG_LEVEL.VERBOSE, "OneSignalRestClient: After con.getResponseCode to: https://api.onesignal.com/" + str);
                    String str4 = com.google.firebase.BuildConfig.FLAVOR;
                    String str5 = ShareTarget.METHOD_GET;
                    if (i2 == 200 || i2 == 202) {
                        OneSignal.LOG_LEVEL log_level = OneSignal.LOG_LEVEL.DEBUG;
                        StringBuilder sb = new StringBuilder();
                        try {
                            sb.append("OneSignalRestClient: Successfully finished request to: https://api.onesignal.com/");
                            sb.append(str);
                            OneSignal.Log(log_level, sb.toString());
                            Scanner scanner = new Scanner(httpURLConnection.getInputStream(), "UTF-8");
                            if (scanner.useDelimiter("\\A").hasNext()) {
                                str4 = scanner.next();
                            }
                            scanner.close();
                            OneSignal.LOG_LEVEL log_level2 = OneSignal.LOG_LEVEL.DEBUG;
                            StringBuilder sb2 = new StringBuilder();
                            sb2.append("OneSignalRestClient: ");
                            if (str2 != null) {
                                str5 = str2;
                            }
                            sb2.append(str5);
                            sb2.append(" RECEIVED JSON: ");
                            sb2.append(str4);
                            OneSignal.Log(log_level2, sb2.toString());
                            if (str3 != null && (headerField = httpURLConnection.getHeaderField("etag")) != null) {
                                OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "OneSignalRestClient: Response has etag of " + headerField + " so caching the response.");
                                OneSignalPrefs.saveString(OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_ETAG_PREFIX + str3, headerField);
                                OneSignalPrefs.saveString(OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_HTTP_CACHE_PREFIX + str3, str4);
                            }
                            callResponseHandlerOnFailure = callResponseHandlerOnSuccess(responseHandler, str4);
                        } catch (Throwable th) {
                            th = th;
                            i2 = i2;
                            try {
                                if (!(th instanceof ConnectException) && !(th instanceof UnknownHostException)) {
                                    OneSignal.Log(OneSignal.LOG_LEVEL.WARN, "OneSignalRestClient: " + str2 + " Error thrown from network stack. ", th);
                                    callResponseHandlerOnFailure = callResponseHandlerOnFailure(responseHandler, i2, null, th);
                                }
                                OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "OneSignalRestClient: Could not send last request, device is offline. Throwable: " + th.getClass().getName());
                                callResponseHandlerOnFailure = callResponseHandlerOnFailure(responseHandler, i2, null, th);
                            } finally {
                                if (httpURLConnection != null) {
                                    httpURLConnection.disconnect();
                                }
                            }
                        }
                    } else if (i2 == 304) {
                        String string2 = OneSignalPrefs.getString(OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_HTTP_CACHE_PREFIX + str3, null);
                        OneSignal.LOG_LEVEL log_level3 = OneSignal.LOG_LEVEL.DEBUG;
                        StringBuilder sb3 = new StringBuilder();
                        sb3.append("OneSignalRestClient: ");
                        if (str2 != null) {
                            str5 = str2;
                        }
                        sb3.append(str5);
                        sb3.append(" - Using Cached response due to 304: ");
                        sb3.append(string2);
                        OneSignal.Log(log_level3, sb3.toString());
                        callResponseHandlerOnFailure = callResponseHandlerOnSuccess(responseHandler, string2);
                    } else {
                        OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "OneSignalRestClient: Failed request to: https://api.onesignal.com/" + str);
                        InputStream errorStream = httpURLConnection.getErrorStream();
                        if (errorStream == null) {
                            errorStream = httpURLConnection.getInputStream();
                        }
                        if (errorStream != null) {
                            Scanner scanner2 = new Scanner(errorStream, "UTF-8");
                            if (scanner2.useDelimiter("\\A").hasNext()) {
                                str4 = scanner2.next();
                            }
                            scanner2.close();
                            OneSignal.Log(OneSignal.LOG_LEVEL.WARN, "OneSignalRestClient: " + str2 + " RECEIVED JSON: " + str4);
                        } else {
                            OneSignal.Log(OneSignal.LOG_LEVEL.WARN, "OneSignalRestClient: " + str2 + " HTTP Code: " + i2 + " No response body!");
                            str4 = null;
                        }
                        callResponseHandlerOnFailure = callResponseHandlerOnFailure(responseHandler, i2, str4, null);
                    }
                } catch (Throwable th2) {
                    th = th2;
                }
            } catch (Throwable th3) {
                th = th3;
            }
        } catch (Throwable th4) {
            th = th4;
            httpURLConnection = null;
        }
    }

    private static Thread callResponseHandlerOnSuccess(final ResponseHandler responseHandler, final String str) {
        if (responseHandler == null) {
            return null;
        }
        Thread thread = new Thread(new Runnable() { // from class: com.onesignal.OneSignalRestClient.5
            @Override // java.lang.Runnable
            public void run() {
                ResponseHandler.this.onSuccess(str);
            }
        }, "OS_REST_SUCCESS_CALLBACK");
        thread.start();
        return thread;
    }

    private static Thread callResponseHandlerOnFailure(final ResponseHandler responseHandler, final int i, final String str, final Throwable th) {
        if (responseHandler == null) {
            return null;
        }
        Thread thread = new Thread(new Runnable() { // from class: com.onesignal.OneSignalRestClient.6
            @Override // java.lang.Runnable
            public void run() {
                ResponseHandler.this.onFailure(i, str, th);
            }
        }, "OS_REST_FAILURE_CALLBACK");
        thread.start();
        return thread;
    }

    private static HttpURLConnection newHttpURLConnection(String str) throws IOException {
        return (HttpURLConnection) new URL(BASE_URL + str).openConnection();
    }
}
