package jb;

import android.content.Context;
import android.content.pm.PackageManager;
import android.net.TrafficStats;
import android.text.TextUtils;
import android.util.JsonReader;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.exoplayer.hls.playlist.HlsMediaPlaylist;
import androidx.media3.exoplayer.rtsp.RtspHeaders;
import com.google.android.gms.common.internal.w;
import com.google.firebase.installations.FirebaseInstallationsException;
import com.google.firebase.installations.remote.InstallationResponse$ResponseCode;
import com.google.firebase.installations.remote.TokenResult$ResponseCode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import org.json.JSONException;
import org.json.JSONObject;
import v6.j;
import w8.k;
import xyz.stream.utils.t;

/* JADX INFO: loaded from: classes2.dex */
public final class c {

    /* JADX INFO: renamed from: d, reason: collision with root package name */
    public static final Pattern f28758d = Pattern.compile("[0-9]+s");

    /* JADX INFO: renamed from: e, reason: collision with root package name */
    public static final Charset f28759e = Charset.forName("UTF-8");

    /* JADX INFO: renamed from: a, reason: collision with root package name */
    public final Context f28760a;

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    public final gb.a f28761b;

    /* JADX INFO: renamed from: c, reason: collision with root package name */
    public final e f28762c = new e();

    public c(Context context, gb.a aVar) {
        this.f28760a = context;
        this.f28761b = aVar;
    }

    private static String availableFirebaseOptions(@Nullable String str, @NonNull String str2, @NonNull String str3) {
        Object[] objArr = new Object[3];
        objArr[0] = str2;
        objArr[1] = str3;
        objArr[2] = TextUtils.isEmpty(str) ? "" : defpackage.e.i(", ", str);
        return String.format("Firebase options used while communicating with Firebase server APIs: %s, %s%s", objArr);
    }

    public static URL b(String str) throws FirebaseInstallationsException {
        try {
            return new URL(String.format("https://%s/%s/%s", "firebaseinstallations.googleapis.com", "v1", str));
        } catch (MalformedURLException e10) {
            throw new FirebaseInstallationsException(e10.getMessage(), FirebaseInstallationsException.Status.f24088b);
        }
    }

    private static JSONObject buildCreateFirebaseInstallationRequestBody(@Nullable String str, @NonNull String str2) {
        try {
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("fid", str);
            jSONObject.put("appId", str2);
            jSONObject.put("authVersion", "FIS_v2");
            jSONObject.put("sdkVersion", "a:18.0.0");
            return jSONObject;
        } catch (JSONException e10) {
            throw new IllegalStateException(e10);
        }
    }

    public static long d(String str) {
        w.b(f28758d.matcher(str).matches(), "Invalid Expiration Timestamp.");
        if (str == null || str.length() == 0) {
            return 0L;
        }
        return Long.parseLong(str.substring(0, str.length() - 1));
    }

    public static a e(HttpURLConnection httpURLConnection) throws IOException {
        InputStream inputStream = httpURLConnection.getInputStream();
        JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, f28759e));
        t tVarA = f.a();
        j jVar = new j();
        jsonReader.beginObject();
        while (jsonReader.hasNext()) {
            String strNextName = jsonReader.nextName();
            if (strNextName.equals("name")) {
                jVar.f33701b = jsonReader.nextString();
            } else if (strNextName.equals("fid")) {
                jVar.f33700a = jsonReader.nextString();
            } else if (strNextName.equals("refreshToken")) {
                jVar.f33704e = jsonReader.nextString();
            } else if (strNextName.equals("authToken")) {
                jsonReader.beginObject();
                while (jsonReader.hasNext()) {
                    String strNextName2 = jsonReader.nextName();
                    if (strNextName2.equals("token")) {
                        tVarA.f36172b = jsonReader.nextString();
                    } else if (strNextName2.equals("expiresIn")) {
                        tVarA.f36173c = Long.valueOf(d(jsonReader.nextString()));
                    } else {
                        jsonReader.skipValue();
                    }
                }
                jVar.f33703d = tVarA.h();
                jsonReader.endObject();
            } else {
                jsonReader.skipValue();
            }
        }
        jsonReader.endObject();
        jsonReader.close();
        inputStream.close();
        InstallationResponse$ResponseCode installationResponse$ResponseCode = InstallationResponse$ResponseCode.f24110a;
        jVar.f33702c = installationResponse$ResponseCode;
        return new a((String) jVar.f33701b, (String) jVar.f33700a, (String) jVar.f33704e, (f) jVar.f33703d, installationResponse$ResponseCode, 0);
    }

    public static b f(HttpURLConnection httpURLConnection) throws IOException {
        InputStream inputStream = httpURLConnection.getInputStream();
        JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, f28759e));
        t tVarA = f.a();
        jsonReader.beginObject();
        while (jsonReader.hasNext()) {
            String strNextName = jsonReader.nextName();
            if (strNextName.equals("token")) {
                tVarA.f36172b = jsonReader.nextString();
            } else if (strNextName.equals("expiresIn")) {
                tVarA.f36173c = Long.valueOf(d(jsonReader.nextString()));
            } else {
                jsonReader.skipValue();
            }
        }
        jsonReader.endObject();
        jsonReader.close();
        inputStream.close();
        tVarA.f36174d = TokenResult$ResponseCode.f24113a;
        return tVarA.h();
    }

    public static void g(HttpURLConnection httpURLConnection) throws IOException {
        try {
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("sdkVersion", "a:18.0.0");
            JSONObject jSONObject2 = new JSONObject();
            jSONObject2.put("installation", jSONObject);
            h(httpURLConnection, jSONObject2.toString().getBytes("UTF-8"));
        } catch (JSONException e10) {
            throw new IllegalStateException(e10);
        }
    }

    public static void h(URLConnection uRLConnection, byte[] bArr) throws IOException {
        OutputStream outputStream = uRLConnection.getOutputStream();
        if (outputStream == null) {
            throw new IOException("Cannot send request to FIS servers. No OutputStream available.");
        }
        GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(outputStream);
        try {
            gZIPOutputStream.write(bArr);
        } finally {
            try {
                gZIPOutputStream.close();
                outputStream.close();
            } catch (IOException unused) {
            }
        }
    }

    private static void logFisCommunicationError(HttpURLConnection httpURLConnection, @Nullable String str, @NonNull String str2, @NonNull String str3) {
        if (TextUtils.isEmpty(readErrorResponse(httpURLConnection))) {
            return;
        }
        availableFirebaseOptions(str, str2, str3);
    }

    @Nullable
    private static String readErrorResponse(HttpURLConnection httpURLConnection) {
        StringBuilder sb;
        InputStream errorStream = httpURLConnection.getErrorStream();
        if (errorStream == null) {
            return null;
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(errorStream, f28759e));
        try {
            try {
                sb = new StringBuilder();
            } catch (IOException unused) {
            }
        } catch (IOException unused2) {
            bufferedReader.close();
        } catch (Throwable th) {
            try {
                bufferedReader.close();
            } catch (IOException unused3) {
            }
            throw th;
        }
        while (true) {
            String line = bufferedReader.readLine();
            if (line == null) {
                break;
            }
            sb.append(line);
            sb.append('\n');
            return null;
        }
        String str = String.format("Error when communicating with the Firebase Installations server API. HTTP response: [%d %s: %s]", Integer.valueOf(httpURLConnection.getResponseCode()), httpURLConnection.getResponseMessage(), sb);
        try {
            bufferedReader.close();
        } catch (IOException unused4) {
        }
        return str;
    }

    private void writeFIDCreateRequestBodyToOutputStream(HttpURLConnection httpURLConnection, @Nullable String str, @NonNull String str2) throws IOException {
        h(httpURLConnection, buildCreateFirebaseInstallationRequestBody(str, str2).toString().getBytes("UTF-8"));
    }

    public final b a(String str, String str2, String str3, String str4) {
        int responseCode;
        b bVarH;
        e eVar = this.f28762c;
        boolean zA = eVar.a();
        FirebaseInstallationsException.Status status = FirebaseInstallationsException.Status.f24088b;
        if (!zA) {
            throw new FirebaseInstallationsException("Firebase Installations Service is unavailable. Please try again later.", status);
        }
        URL urlB = b(String.format("projects/%s/installations/%s/authTokens:generate", str3, str2));
        for (int i10 = 0; i10 <= 1; i10++) {
            TrafficStats.setThreadStatsTag(32771);
            HttpURLConnection httpURLConnectionC = c(urlB, str);
            try {
                try {
                    httpURLConnectionC.setRequestMethod(HlsMediaPlaylist.Interstitial.CUE_TRIGGER_POST);
                    httpURLConnectionC.addRequestProperty(RtspHeaders.AUTHORIZATION, "FIS_v2 " + str4);
                    httpURLConnectionC.setDoOutput(true);
                    g(httpURLConnectionC);
                    responseCode = httpURLConnectionC.getResponseCode();
                    eVar.b(responseCode);
                } finally {
                    httpURLConnectionC.disconnect();
                    TrafficStats.clearThreadStatsTag();
                }
            } catch (IOException | AssertionError unused) {
            }
            if (responseCode < 200 || responseCode >= 300) {
                logFisCommunicationError(httpURLConnectionC, null, str, str3);
                if (responseCode == 401 || responseCode == 404) {
                    t tVarA = f.a();
                    tVarA.f36174d = TokenResult$ResponseCode.f24115c;
                    bVarH = tVarA.h();
                } else {
                    if (responseCode == 429) {
                        throw new FirebaseInstallationsException("Firebase servers have received too many requests from this client in a short period of time. Please try again later.", FirebaseInstallationsException.Status.f24089c);
                    }
                    if (responseCode < 500 || responseCode >= 600) {
                        t tVarA2 = f.a();
                        tVarA2.f36174d = TokenResult$ResponseCode.f24114b;
                        bVarH = tVarA2.h();
                    }
                }
            } else {
                bVarH = f(httpURLConnectionC);
            }
            return bVarH;
        }
        throw new FirebaseInstallationsException("Firebase Installations Service is unavailable. Please try again later.", status);
    }

    public final HttpURLConnection c(URL url, String str) throws FirebaseInstallationsException {
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.addRequestProperty(RtspHeaders.CONTENT_TYPE, "application/json");
            httpURLConnection.addRequestProperty(RtspHeaders.ACCEPT, "application/json");
            httpURLConnection.addRequestProperty(RtspHeaders.CONTENT_ENCODING, "gzip");
            httpURLConnection.addRequestProperty(RtspHeaders.CACHE_CONTROL, "no-cache");
            Context context = this.f28760a;
            httpURLConnection.addRequestProperty("X-Android-Package", context.getPackageName());
            eb.f fVar = (eb.f) this.f28761b.get();
            if (fVar != null) {
                try {
                    httpURLConnection.addRequestProperty("x-firebase-client", (String) k.a(((eb.d) fVar).a()));
                } catch (InterruptedException unused) {
                    Thread.currentThread().interrupt();
                } catch (ExecutionException unused2) {
                }
            }
            String string = null;
            try {
                byte[] packageCertificateHashBytes = i8.a.getPackageCertificateHashBytes(context, context.getPackageName());
                if (packageCertificateHashBytes == null) {
                    context.getPackageName();
                } else {
                    int length = packageCertificateHashBytes.length;
                    StringBuilder sb = new StringBuilder(length + length);
                    for (int i10 = 0; i10 < length; i10++) {
                        char[] cArr = i8.f.f26578a;
                        sb.append(cArr[(packageCertificateHashBytes[i10] & 240) >>> 4]);
                        sb.append(cArr[packageCertificateHashBytes[i10] & 15]);
                    }
                    string = sb.toString();
                }
            } catch (PackageManager.NameNotFoundException unused3) {
                context.getPackageName();
            }
            httpURLConnection.addRequestProperty("X-Android-Cert", string);
            httpURLConnection.addRequestProperty("x-goog-api-key", str);
            return httpURLConnection;
        } catch (IOException unused4) {
            throw new FirebaseInstallationsException("Firebase Installations Service is unavailable. Please try again later.", FirebaseInstallationsException.Status.f24088b);
        }
    }

    @NonNull
    public d createFirebaseInstallation(@NonNull String str, @Nullable String str2, @NonNull String str3, @NonNull String str4, @Nullable String str5) throws FirebaseInstallationsException {
        String str6 = str;
        e eVar = this.f28762c;
        boolean zA = eVar.a();
        FirebaseInstallationsException.Status status = FirebaseInstallationsException.Status.f24088b;
        if (!zA) {
            throw new FirebaseInstallationsException("Firebase Installations Service is unavailable. Please try again later.", status);
        }
        URL urlB = b(String.format("projects/%s/installations", str3));
        for (int i10 = 0; i10 <= 1; i10++) {
            TrafficStats.setThreadStatsTag(32769);
            HttpURLConnection httpURLConnectionC = c(urlB, str6);
            try {
                try {
                    httpURLConnectionC.setRequestMethod(HlsMediaPlaylist.Interstitial.CUE_TRIGGER_POST);
                    httpURLConnectionC.setDoOutput(true);
                    if (str5 != null) {
                        httpURLConnectionC.addRequestProperty("x-goog-fis-android-iid-migration-auth", str5);
                    }
                } catch (IOException | AssertionError unused) {
                }
                try {
                    writeFIDCreateRequestBodyToOutputStream(httpURLConnectionC, str2, str4);
                    int responseCode = httpURLConnectionC.getResponseCode();
                    eVar.b(responseCode);
                    if (responseCode >= 200 && responseCode < 300) {
                        return e(httpURLConnectionC);
                    }
                    try {
                        logFisCommunicationError(httpURLConnectionC, str4, str6, str3);
                        if (responseCode == 429) {
                            throw new FirebaseInstallationsException("Firebase servers have received too many requests from this client in a short period of time. Please try again later.", FirebaseInstallationsException.Status.f24089c);
                        }
                        if (responseCode < 500 || responseCode >= 600) {
                            j jVar = new j();
                            InstallationResponse$ResponseCode installationResponse$ResponseCode = InstallationResponse$ResponseCode.f24111b;
                            jVar.f33702c = installationResponse$ResponseCode;
                            return new a((String) jVar.f33701b, (String) jVar.f33700a, (String) jVar.f33704e, (f) jVar.f33703d, installationResponse$ResponseCode, 0);
                        }
                    } catch (IOException | AssertionError unused2) {
                    }
                } catch (IOException | AssertionError unused3) {
                }
            } finally {
                httpURLConnectionC.disconnect();
                TrafficStats.clearThreadStatsTag();
            }
        }
        throw new FirebaseInstallationsException("Firebase Installations Service is unavailable. Please try again later.", status);
    }
}
