导航菜单

页面标题

页面副标题

xDrip+ v04633772025.07.16 - CareLinkAuthenticator.java 源代码

正在查看: xDrip+ v04633772025.07.16 应用的 CareLinkAuthenticator.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.eveningoutpost.dexdrip.cgm.carelinkfollow.auth;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.UrlQuerySanitizer;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.webkit.CookieManager;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import androidx.appcompat.widget.LinearLayoutCompat;
import com.eveningoutpost.dexdrip.models.UserError;
import com.eveningoutpost.dexdrip.xdrip;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import javax.security.auth.x500.X500Principal;
import okhttp3.Cookie;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;

public class CareLinkAuthenticator {
    protected static final String[] ANDROID_MODELS = {"SM-G973F", "SM-G988U1", "SM-G981W", "SM-G9600"};
    protected static final SimpleDateFormat[] VALIDTO_DATE_FORMATS;
    private String carelinkCountry;
    private CarePartnerAppConfig carepartnerAppConfig;
    private CareLinkCredentialStore credentialStore;
    private AlertDialog progressDialog;
    private final Semaphore available = new Semaphore(0, true);
    private String authCode = null;
    private OkHttpClient httpClient = null;
    private boolean authWebViewCancelled = false;
    private boolean carelinkCommunicationError = false;

    static {
        Locale locale = Locale.ENGLISH;
        VALIDTO_DATE_FORMATS = new SimpleDateFormat[]{new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy", locale), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", locale), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz", locale), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", locale), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", locale), new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")};
    }

    public CareLinkAuthenticator(String str, CareLinkCredentialStore careLinkCredentialStore) {
        this.carelinkCountry = str;
        this.credentialStore = careLinkCredentialStore;
    }

    public boolean authenticate(Activity activity, CareLinkAuthType careLinkAuthType) throws InterruptedException {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            throw new RuntimeException("don't call authenticate() from the main thread.");
        }
        int i = AnonymousClass9.$SwitchMap$com$eveningoutpost$dexdrip$cgm$carelinkfollow$auth$CareLinkAuthType[careLinkAuthType.ordinal()];
        if (i == 1) {
            authenticateAsBrowser(activity);
        } else if (i == 2) {
            authenticateAsCpApp(activity);
        }
        return this.credentialStore.getAuthStatus() == 2;
    }

    static class AnonymousClass9 {
        static final int[] $SwitchMap$com$eveningoutpost$dexdrip$cgm$carelinkfollow$auth$CareLinkAuthType;

        static {
            int[] iArr = new int[CareLinkAuthType.values().length];
            $SwitchMap$com$eveningoutpost$dexdrip$cgm$carelinkfollow$auth$CareLinkAuthType = iArr;
            try {
                iArr[CareLinkAuthType.Browser.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$cgm$carelinkfollow$auth$CareLinkAuthType[CareLinkAuthType.MobileApp.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
        }
    }

    public boolean refreshToken() {
        if (this.credentialStore.getCredential() == null || this.credentialStore.getCredential().authType == null || this.credentialStore.getAuthStatus() == 0) {
            return false;
        }
        int i = AnonymousClass9.$SwitchMap$com$eveningoutpost$dexdrip$cgm$carelinkfollow$auth$CareLinkAuthType[this.credentialStore.getCredential().authType.ordinal()];
        if (i == 1) {
            return refreshBrowserToken();
        }
        if (i != 2) {
            return false;
        }
        return refreshCpAppToken();
    }

    private void authenticateAsCpApp(final Activity activity) {
        try {
            this.carelinkCommunicationError = false;
            showProgressDialog(activity);
            String generateDeviceId = generateDeviceId();
            String generateAndroidModel = generateAndroidModel();
            loadAppConfig();
            JsonObject createClientCredential = createClientCredential(generateDeviceId);
            String asString = createClientCredential.get("client_id").getAsString();
            String asString2 = createClientCredential.get("client_secret").getAsString();
            UserError.Log.d("CareLinkAuthenticator", "Prepare authentication");
            String generateRandomDataBase64url = generateRandomDataBase64url(32);
            final String prepareAuth = prepareAuth(asString, generateRandomDataBase64url);
            hideProgressDialog();
            UserError.Log.d("CareLinkAuthenticator", "Start browser login");
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    CareLinkAuthenticator.this.showCpAppAuthPage(activity, prepareAuth);
                }
            });
            this.available.acquire();
            if (!this.authWebViewCancelled && !this.carelinkCommunicationError) {
                showProgressDialog(activity);
                UserError.Log.d("CareLinkAuthenticator", "Register device");
                Response registerDevice = registerDevice(generateDeviceId, generateAndroidModel, asString, asString2, this.authCode, generateRandomDataBase64url);
                String header = registerDevice.header("mag-identifier");
                String header2 = registerDevice.header("id-token");
                String header3 = registerDevice.header("id-token-type");
                UserError.Log.d("CareLinkAuthenticator", "Get access token");
                JsonObject accessToken = getAccessToken(asString, asString2, header, header2, header3);
                UserError.Log.d("CareLinkAuthenticator", "Store credentials");
                this.credentialStore.setMobileAppCredential(this.carelinkCountry, generateDeviceId, generateAndroidModel, asString, asString2, header, accessToken.get("access_token").getAsString(), accessToken.get("refresh_token").getAsString(), new Date(Calendar.getInstance().getTime().getTime() + (accessToken.get("expires_in").getAsInt() * 1000)), new Date(Calendar.getInstance().getTime().getTime() + (this.carepartnerAppConfig.getRefreshLifetimeSec() * 1000)));
                hideProgressDialog();
            }
        } catch (Exception e) {
            UserError.Log.e("CareLinkAuthenticator", "Error authenticating as CpApp. Details: \r\n " + e.getMessage());
            this.carelinkCommunicationError = true;
            hideProgressDialog();
        }
        if (this.carelinkCommunicationError) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    new AlertDialog.Builder(activity).setTitle("Communication error!").setMessage("Error communicating with CareLink Server! Please try again later!").setCancelable(true).setNeutralButton(2131755953, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    }).show();
                }
            });
        }
    }

    private void authenticateAsBrowser(final Activity activity) throws InterruptedException {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                CareLinkAuthenticator.this.showBrowserAuthPage(activity, "");
            }
        });
        this.available.acquire();
    }

    private OkHttpClient getHttpClient() {
        if (this.httpClient == null) {
            this.httpClient = new OkHttpClient();
        }
        return this.httpClient;
    }

    private boolean loadAppConfig() throws IOException {
        if (this.carepartnerAppConfig != null) {
            return true;
        }
        this.carepartnerAppConfig = new CarePartnerAppConfig();
        UserError.Log.d("CareLinkAuthenticator", "Get region config");
        this.carepartnerAppConfig.regionConfig = getCpAppRegionConfig();
        UserError.Log.d("CareLinkAuthenticator", "Get SSO config");
        CarePartnerAppConfig carePartnerAppConfig = this.carepartnerAppConfig;
        carePartnerAppConfig.ssoConfig = getCpAppSSOConfig(carePartnerAppConfig.getSSOConfigUrl());
        return true;
    }

    private JsonObject getAccessToken(String str, String str2, String str3, String str4, String str5) throws IOException {
        return getToken(str, str2, str3, str4, str5, null);
    }

    private JsonObject refreshToken(String str, String str2, String str3, String str4) throws IOException {
        return getToken(str, str2, str3, null, null, str4);
    }

    private JsonObject getToken(String str, String str2, String str3, String str4, String str5, String str6) throws IOException {
        FormBody.Builder add = new FormBody.Builder().add("client_id", str).add("client_secret", str2);
        if (str4 != null) {
            add.add("assertion", str4).add("grant_type", str5).add("scope", this.carepartnerAppConfig.getOAuthScope());
        } else {
            add.add("refresh_token", str6).add("grant_type", "refresh_token");
        }
        return callSsoRestApi(new Request.Builder().post(add.build()).addHeader("mag-identifier", str3).header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"), this.carepartnerAppConfig.getOAuthTokenEndpoint(), null);
    }

    private Response registerDevice(String str, String str2, String str3, String str4, String str5, String str6) throws IOException {
        String str7;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            str7 = createTrimmedCsr(keyPairGenerator.genKeyPair(), "SHA256withRSA", "socialLogin", str, str2, "Medtronic");
        } catch (Exception e) {
            UserError.Log.e("CareLinkAuthenticator", "Error creating CSR! Details: \r\n" + e.getMessage());
            str7 = null;
        }
        return callSsoApi(new Request.Builder().post(RequestBody.create((MediaType) null, str7)).addHeader("device-id", Base64.encodeToString(str.getBytes(StandardCharsets.UTF_8), 2)).addHeader("device-name", Base64.encodeToString(str2.getBytes(StandardCharsets.UTF_8), 2)).addHeader("authorization", "Bearer " + str5).addHeader("client-authorization", "Basic " + Base64.encodeToString((str3 + ":" + str4).getBytes(StandardCharsets.UTF_8), 2)).addHeader("cert-format", "pem").addHeader("create-session", "true").addHeader("code-verifier", str6).addHeader("redirect-uri", this.carepartnerAppConfig.getOAuthRedirectUri()), this.carepartnerAppConfig.getMagDeviceRegisterEndpoint(), null);
    }

    private String createTrimmedCsr(KeyPair keyPair, String str, String str2, String str3, String str4, String str5) throws IOException, OperatorCreationException {
        PKCS10CertificationRequest build = new JcaPKCS10CertificationRequestBuilder(new X500Principal("CN=" + str2 + ", OU=" + str3 + ", DC=" + str4 + ", O=" + str5), keyPair.getPublic()).build(new JcaContentSignerBuilder(str).build(keyPair.getPrivate()));
        StringWriter stringWriter = new StringWriter();
        JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(stringWriter);
        jcaPEMWriter.writeObject(build);
        jcaPEMWriter.close();
        return stringWriter.toString().replaceAll("-----.*-----", "").replaceAll("\\r", "").replaceAll("\\n", "");
    }

    private String prepareAuth(String str, String str2) throws IOException {
        String str3;
        try {
            str3 = Base64.encodeToString(MessageDigest.getInstance("SHA-256").digest(str2.getBytes("ISO_8859_1")), 11);
        } catch (Exception unused) {
            str3 = null;
        }
        HashMap hashMap = new HashMap();
        hashMap.put("client_id", str);
        hashMap.put("response_type", "code");
        hashMap.put("display", "social_login");
        hashMap.put("scope", this.carepartnerAppConfig.getOAuthScope());
        hashMap.put("code_challenge", str3);
        hashMap.put("code_challenge_method", "S256");
        hashMap.put("redirect_uri", this.carepartnerAppConfig.getOAuthRedirectUri());
        hashMap.put("state", generateRandomDataBase64url(32));
        Iterator<JsonElement> it = callSsoRestApi(new Request.Builder().get(), this.carepartnerAppConfig.getOAuthAuthEndpoint(), hashMap).get("providers").getAsJsonArray().iterator();
        while (it.hasNext()) {
            JsonElement next = it.next();
            if (next.getAsJsonObject().get("provider").getAsJsonObject().get("id").getAsString().contentEquals("enterprise")) {
                return next.getAsJsonObject().get("provider").getAsJsonObject().get("auth_url").getAsString();
            }
        }
        return null;
    }

    private JsonObject createClientCredential(String str) throws IOException {
        return callSsoRestApi(new Request.Builder().post(new FormBody.Builder().add("client_id", this.carepartnerAppConfig.getClientId()).add("nonce", UUID.randomUUID().toString()).build()).addHeader("device-id", Base64.encodeToString(str.getBytes(StandardCharsets.UTF_8), 10)), this.carepartnerAppConfig.getMagCredentialInitEndpoint(), null);
    }

    private String generateDeviceId() {
        try {
            byte[] digest = MessageDigest.getInstance("SHA-256").digest(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder(digest.length);
            for (byte b : digest) {
                sb.append(String.format("%02x", Byte.valueOf(b)));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            UserError.Log.e("CareLinkAuthenticator", "Error generating deviceId! Details: \r\n" + e.getMessage());
            return null;
        }
    }

    private String generateAndroidModel() {
        String[] strArr = ANDROID_MODELS;
        return strArr[new Random().nextInt(strArr.length)];
    }

    private String generateRandomDataBase64url(int i) {
        byte[] bArr = new byte[i];
        new SecureRandom().nextBytes(bArr);
        return Base64.encodeToString(bArr, 11);
    }

    private JsonObject callSsoRestApi(Request.Builder builder, String str, Map<String, String> map) throws IOException {
        Response callSsoApi = callSsoApi(builder, str, map);
        if (callSsoApi.isSuccessful()) {
            return JsonParser.parseString(callSsoApi.body().string()).getAsJsonObject();
        }
        return null;
    }

    private Response callSsoApi(Request.Builder builder, String str, Map<String, String> map) throws IOException {
        HttpUrl.Builder addPathSegments = new HttpUrl.Builder().scheme("https").host(this.carepartnerAppConfig.getSSOServerHost()).addPathSegments(this.carepartnerAppConfig.getSSOServerPrefix()).addPathSegments(str);
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                addPathSegments.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }
        builder.url(addPathSegments.build());
        return getHttpClient().newCall(builder.build()).execute();
    }

    private boolean refreshCpAppToken() {
        try {
            loadAppConfig();
            JsonObject refreshToken = refreshToken(this.credentialStore.getCredential().clientId, this.credentialStore.getCredential().clientSecret, this.credentialStore.getCredential().magIdentifier, this.credentialStore.getCredential().refreshToken);
            this.credentialStore.updateMobileAppCredential(refreshToken.get("access_token").getAsString(), new Date(Calendar.getInstance().getTime().getTime() + (refreshToken.get("expires_in").getAsInt() * 1000)), new Date(Calendar.getInstance().getTime().getTime() + (this.carepartnerAppConfig.getRefreshLifetimeSec() * 1000)), refreshToken.get("refresh_token").getAsString());
            return true;
        } catch (Exception e) {
            UserError.Log.e("CareLinkAuthenticator", "Error refreshing CpApp token! Details: \r\n" + e.getMessage());
            return false;
        }
    }

    private boolean refreshBrowserToken() {
        if (this.credentialStore.getAuthStatus() == 0) {
            return false;
        }
        EditableCookieJar editableCookieJar = new EditableCookieJar();
        OkHttpClient build = new OkHttpClient.Builder().cookieJar(editableCookieJar).build();
        editableCookieJar.AddCookies(this.credentialStore.getCredential().cookies);
        try {
            Response execute = build.newCall(new Request.Builder().url(new HttpUrl.Builder().scheme("https").host(careLinkServer()).addPathSegments("patient/sso/reauth").build()).post(RequestBody.create((MediaType) null, new byte[0])).addHeader("Accept", "application/json, text/plain, */*").addHeader("Accept-Language", "en;q=0.9, *;q=0.8").addHeader("Connection", "keep-alive").addHeader("Authorization", this.credentialStore.getCredential().getAuthorizationFieldValue()).addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Mobile Safari/537.36").addHeader("Sec-Ch-Ua", "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"").build()).execute();
            if (!execute.isSuccessful() || !editableCookieJar.contains("auth_tmp_token") || !editableCookieJar.contains("c_token_valid_to")) {
                return false;
            }
            this.credentialStore.updateBrowserCredential(editableCookieJar.getCookies("auth_tmp_token").get(0).value(), parseValidTo(editableCookieJar.getCookies("c_token_valid_to").get(0).value()), parseValidTo(editableCookieJar.getCookies("c_token_valid_to").get(0).value()), (Cookie[]) editableCookieJar.getAllCookies().toArray(new Cookie[0]));
            execute.close();
            return this.credentialStore.getAuthStatus() == 2;
        } catch (IOException unused) {
            return false;
        }
    }

    private void showProgressDialog(final Activity activity) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                CareLinkAuthenticator.this.getProgressDialog(activity).show();
            }
        });
    }

    private void hideProgressDialog() {
        AlertDialog alertDialog = this.progressDialog;
        if (alertDialog == null || !alertDialog.isShowing()) {
            return;
        }
        this.progressDialog.dismiss();
    }

    public AlertDialog getProgressDialog(Activity activity) {
        if (this.progressDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle(xdrip.gs(2131755295));
            ProgressBar progressBar = new ProgressBar(activity);
            progressBar.setLayoutParams(new LinearLayout.LayoutParams(-2, -2));
            builder.setView(progressBar);
            this.progressDialog = builder.create();
        }
        return this.progressDialog;
    }

    public void showBrowserAuthPage(Activity activity, String str) {
        final Dialog dialog = new Dialog(activity);
        showAuthWebView(dialog, str, new WebViewClient() {
            @Override
            public void onPageStarted(WebView webView, String str2, Bitmap bitmap) {
                if (CareLinkAuthenticator.this.extractBrowserLoginCookies(str2).booleanValue()) {
                    dialog.dismiss();
                }
            }
        });
    }

    public void showCpAppAuthPage(Activity activity, String str) {
        final Dialog dialog = new Dialog(activity);
        showAuthWebView(dialog, str, new WebViewClient() {
            @Override
            public void onPageStarted(WebView webView, String str2, Bitmap bitmap) {
                if (CareLinkAuthenticator.this.extractCpAppAuthCode(str2)) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                if (webResourceError.getErrorCode() == -6) {
                    CareLinkAuthenticator.this.carelinkCommunicationError = true;
                    dialog.dismiss();
                }
            }
        });
    }

    private void showAuthWebView(Dialog dialog, String str, WebViewClient webViewClient) {
        this.authWebViewCancelled = false;
        LinearLayoutCompat linearLayoutCompat = new LinearLayoutCompat(dialog.getContext());
        WebView webView = new WebView(dialog.getContext());
        webView.setLayoutParams(new LinearLayoutCompat.LayoutParams(-1, -1));
        linearLayoutCompat.addView(webView);
        dialog.setContentView(linearLayoutCompat);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                CareLinkAuthenticator.this.unlock();
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                CareLinkAuthenticator.this.authWebViewCancelled = true;
            }
        });
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Mobile Safari/537.36");
        webView.loadUrl(str);
        webView.setWebViewClient(webViewClient);
        dialog.setCancelable(true);
        dialog.getWindow().setLayout(-1, -1);
        dialog.show();
    }

    public boolean extractCpAppAuthCode(String str) {
        if (!str.contains(this.carepartnerAppConfig.getOAuthRedirectUri())) {
            return false;
        }
        try {
            UrlQuerySanitizer urlQuerySanitizer = new UrlQuerySanitizer();
            urlQuerySanitizer.setAllowUnregisteredParamaters(true);
            urlQuerySanitizer.parseUrl(str);
            this.authCode = urlQuerySanitizer.getValue("code");
        } catch (Exception e) {
            UserError.Log.e("CareLinkAuthenticator", "Error extracting authCode! Details: \r\n" + e.getMessage());
        }
        return true;
    }

    private JsonObject getCpAppRegionConfig() throws IOException {
        JsonObject configJson = getConfigJson("https://clcloud.minimed.eu/connect/carepartner/v11/discover/android/3.2");
        JsonArray asJsonArray = configJson.getAsJsonArray("supportedCountries");
        JsonArray asJsonArray2 = configJson.getAsJsonArray("CP");
        Iterator<JsonElement> it = asJsonArray.iterator();
        while (it.hasNext()) {
            JsonElement next = it.next();
            JsonObject asJsonObject = next.getAsJsonObject();
            String str = this.carelinkCountry;
            Locale locale = Locale.ROOT;
            if (asJsonObject.has(str.toUpperCase(locale))) {
                String asString = next.getAsJsonObject().get(this.carelinkCountry.toUpperCase(locale)).getAsJsonObject().get("region").getAsString();
                Iterator<JsonElement> it2 = asJsonArray2.iterator();
                while (it2.hasNext()) {
                    JsonElement next2 = it2.next();
                    if (next2.getAsJsonObject().get("region").getAsString().contentEquals(asString)) {
                        return next2.getAsJsonObject();
                    }
                }
            }
        }
        return null;
    }

    private JsonObject getCpAppSSOConfig(String str) throws IOException {
        return getConfigJson(str);
    }

    private JsonObject getConfigJson(String str) throws IOException {
        return JsonParser.parseString(getHttpClient().newCall(new Request.Builder().url(str).get().build()).execute().body().string()).getAsJsonObject();
    }

    private String careLinkServer() {
        return this.carelinkCountry.equals("us") ? "carelink.minimed.com" : "carelink.minimed.eu";
    }

    public Boolean extractBrowserLoginCookies(String str) {
        String cookie = CookieManager.getInstance().getCookie(str);
        if (cookie != null && cookie.contains("auth_tmp_token") && cookie.contains("c_token_valid_to")) {
            String host = HttpUrl.parse(str).host();
            ArrayList arrayList = new ArrayList();
            String str2 = null;
            Date date = null;
            for (String str3 : cookie.split("; ")) {
                String[] split = str3.split("=");
                Cookie.Builder domain = new Cookie.Builder().name(split[0]).value(split[1]).path("/").domain(host);
                if (split[0].contains("auth_tmp_token")) {
                    domain.secure();
                    str2 = split[1];
                }
                if (split[0].contains("c_token_valid_to")) {
                    Date parseValidTo = parseValidTo(split[1]);
                    domain.secure();
                    date = parseValidTo;
                }
                arrayList.add(domain.build());
            }
            if (date.getTime() < System.currentTimeMillis()) {
                return Boolean.FALSE;
            }
            this.credentialStore.setBrowserCredential(this.carelinkCountry, str2, date, date, (Cookie[]) arrayList.toArray(new Cookie[0]));
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public void unlock() {
        if (this.available.availablePermits() <= 0) {
            this.available.release();
        }
    }

    private Date parseValidTo(String str) {
        for (SimpleDateFormat simpleDateFormat : VALIDTO_DATE_FORMATS) {
            try {
                return simpleDateFormat.parse(str);
            } catch (Exception unused) {
            }
        }
        return null;
    }
}