导航菜单

页面标题

页面副标题

Clash Legends v0.0.1 - BaseUtils.java 源代码

正在查看: Clash Legends v0.0.1 应用的 BaseUtils.java JAVA 源代码文件

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


package com.razorpay;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.payu.checkoutpro.utils.PayUCheckoutProConstants;
import com.payu.india.Payu.PayuConstants;
import com.razorpay.AdvertisingIdUtil;
import in.juspay.godel.core.Constants;
import in.juspay.godel.ui.OnScreenDisplay;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import kotlinx.coroutines.scheduling.WorkQueueKt;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

class BaseUtils {
    static final boolean $assertionsDisabled = false;
    static String ipAddress;
    private static String PERMISSION_DISABLED = "permission disabled";
    private static boolean sWebViewDebuggingEnabled = ConfigDroid.ENABLE_WEBVIEW_DEBUGGING.booleanValue();
    private static boolean isCompatibleWithGooglePay = true;

    BaseUtils() {
    }

    static String constructBasicAuth(String merchantKey) throws UnsupportedEncodingException {
        String basicAuthKey = merchantKey + ":";
        byte[] data = basicAuthKey.getBytes("UTF-8");
        String auth = Base64.encodeToString(data, 2);
        return auth;
    }

    static boolean hasPermission(Context context, String permission) {
        try {
            return context.checkCallingOrSelfPermission(permission) == 0;
        } catch (Exception e) {
            AnalyticsUtil.reportError(e, "critical", e.getMessage());
            return false;
        }
    }

    static String getKeyId(Context context) {
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), WorkQueueKt.BUFFER_CAPACITY);
            if (appInfo.metaData == null) {
                return null;
            }
            String keyId = appInfo.metaData.getString("com.razorpay.ApiKey");
            Logger.d(keyId);
            return keyId;
        } catch (PackageManager.NameNotFoundException e) {
            AnalyticsUtil.reportError(e, "critical", e.getMessage());
            return null;
        }
    }

    static HashMap<String, String> getAllPluginsFromManifest(Context context) {
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), WorkQueueKt.BUFFER_CAPACITY);
            if (appInfo.metaData == null) {
                return null;
            }
            HashMap<String, String> pluginMap = new HashMap<>();
            Set<String> keys = appInfo.metaData.keySet();
            for (String key : keys) {
                if (key.contains("com.razorpay.plugin.") && appInfo.metaData.getString(key) != null) {
                    pluginMap.put(key, appInfo.metaData.getString(key));
                }
            }
            return pluginMap;
        } catch (PackageManager.NameNotFoundException e) {
            AnalyticsUtil.reportError(e, "critical", e.getMessage());
            return null;
        }
    }

    private static void setBaseWebViewSettings() {
        WebView.setWebContentsDebuggingEnabled(sWebViewDebuggingEnabled);
    }

    private static void enableJavaScriptInWebView(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
    }

    static void setWebViewSettings(Context context, WebView webView, boolean disableCache) {
        setBaseWebViewSettings();
        enableJavaScriptInWebView(webView);
        CookieManager.getInstance().setAcceptCookie(true);
        webView.setTag("");
        WebSettings settings = webView.getSettings();
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setTextZoom(100);
        String databasePath = context.getApplicationContext().getDir("database", 0).getPath();
        if (Build.VERSION.SDK_INT < 24) {
            settings.setGeolocationDatabasePath(databasePath);
        }
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptThirdPartyCookies(webView, true);
        if (disableCache) {
            settings.setCacheMode(2);
        }
        settings.setSaveFormData(false);
        webView.addJavascriptInterface(new StorageBridge(context), "StorageBridge");
    }

    static boolean hasFeature(Context context, String feature) {
        return context.getPackageManager().hasSystemFeature(feature);
    }

    static <T> T getSystemService(Context context, String str) {
        return (T) context.getApplicationContext().getSystemService(str);
    }

    static int getNetworkType(Context context) {
        NetworkType networkType = getDataNetworkType(context);
        if (networkType == NetworkType.WIFI) {
            return 0;
        }
        if (networkType == NetworkType.BLUETOOTH) {
            return 1;
        }
        if (networkType == NetworkType.CELLULAR) {
            String cellularNetworkType = getCellularNetworkType(context);
            if (cellularNetworkType.equalsIgnoreCase("2G")) {
                return 2;
            }
            if (cellularNetworkType.equalsIgnoreCase("3G")) {
                return 3;
            }
            if (cellularNetworkType.equalsIgnoreCase("4G")) {
                return 4;
            }
            return -1;
        }
        return -1;
    }

    static String getCellularNetworkType(Context context) {
        try {
            TelephonyManager mTelephonyManager = (TelephonyManager) context.getSystemService("phone");
            int networkType = mTelephonyManager.getNetworkType();
            switch (networkType) {
            }
            return Constants.NA;
        } catch (Exception exception) {
            AnalyticsUtil.reportError(exception, "warning", exception.getLocalizedMessage());
            return Constants.NA;
        }
    }

    static String getCellularNetworkProviderName(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(context, "phone");
        if (telephonyManager != null) {
            return telephonyManager.getNetworkOperatorName();
        }
        return "unknown";
    }

    static NetworkType getDataNetworkType(Context context) {
        ConnectivityManager connectivityManager;
        if (hasPermission(context, "android.permission.ACCESS_NETWORK_STATE") && (connectivityManager = (ConnectivityManager) getSystemService(context, "connectivity")) != null) {
            NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(1);
            if (wifiInfo != null && wifiInfo.isConnected()) {
                return NetworkType.WIFI;
            }
            NetworkInfo bluetoothInfo = connectivityManager.getNetworkInfo(7);
            if (bluetoothInfo != null && bluetoothInfo.isConnected()) {
                return NetworkType.BLUETOOTH;
            }
            NetworkInfo cellularInfo = connectivityManager.getNetworkInfo(0);
            if (cellularInfo != null && cellularInfo.isConnected()) {
                return NetworkType.CELLULAR;
            }
        }
        return NetworkType.UNKNOWN;
    }

    static String getLocale() {
        return Locale.getDefault().getLanguage() + "-" + Locale.getDefault().getCountry();
    }

    static ArrayList<String> jsonStringArrayToArrayList(JSONArray jsonArray) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            list.add(jsonArray.getString(i));
        }
        return list;
    }

    static String getAppBuildType(Context context) {
        if ((context.getApplicationInfo().flags & 2) != 0) {
            return "development";
        }
        return "production";
    }

    static CharSequence getWebViewUserAgent(Context context) {
        return AnalyticsUtil.returnUndefinedIfNull(new WebView(context).getSettings().getUserAgentString());
    }

    static boolean isDeviceHaveCorrectTlsVersion() {
        String[] protocols;
        try {
            SSLParameters sslParameters = SSLContext.getDefault().getDefaultSSLParameters();
            protocols = sslParameters.getProtocols();
        } catch (NoSuchAlgorithmException e) {
            AnalyticsUtil.reportError(e, "critical", e.getMessage());
        }
        if (protocols == null) {
            return false;
        }
        for (String protocol : protocols) {
            if (protocol.startsWith("TLS") && !protocol.equalsIgnoreCase("TLSv1")) {
                return true;
            }
        }
        return false;
    }

    static void setup() {
        AnalyticsUtil.reset();
    }

    public static double round(double value, int places) {
        if (places < 0) {
            throw new IllegalArgumentException();
        }
        BigDecimal bd = new BigDecimal(value);
        return bd.setScale(places, RoundingMode.HALF_UP).doubleValue();
    }

    public static String nanoTimeToSecondsString(long nanoTime, int places) {
        double seconds = nanoTime / 1.0E9d;
        return "" + round(seconds, places);
    }

    static boolean isMerchantAppDebuggable(Context context) {
        return (context.getApplicationInfo().flags & 2) != 0;
    }

    static Certificate getX509Certificate(SslCertificate sslCertificate) {
        Bundle bundle = SslCertificate.saveState(sslCertificate);
        byte[] bytes = bundle.getByteArray("x509-certificate");
        if (bytes == null) {
            return null;
        }
        try {
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            return certFactory.generateCertificate(new ByteArrayInputStream(bytes));
        } catch (CertificateException e) {
            AnalyticsUtil.reportError(e, "critical", e.getLocalizedMessage());
            return null;
        }
    }

    static String makeErrorPayload(String errorCode, String errorDescription) {
        try {
            JSONObject errorObj = new JSONObject();
            JSONObject payload = new JSONObject();
            payload.put(com.instamojo.android.helpers.Constants.KEY_CODE, errorCode);
            payload.put(PayuConstants.DESCRIPTION, errorDescription);
            errorObj.put("error", payload);
            return errorObj.toString();
        } catch (JSONException e) {
            AnalyticsUtil.reportError(e, "error:exception", e.getMessage());
            e.printStackTrace();
            return "{\"error\":{\"code\": \"BAD_REQUEST_ERROR\", \"description\": \"An unknown error occurred.\"}}";
        }
    }

    static PublicKey constructPublicKey(String key) {
        try {
            byte[] byteKey = Base64.decode(key.getBytes(), 0);
            X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePublic(X509publicKey);
        } catch (Exception e) {
            return null;
        }
    }

    private static Boolean isUserRegisteredOnTruePay(Context context) {
        try {
            int settingReceived = context.getPackageManager().getComponentEnabledSetting(new ComponentName("com.truecaller", "com.truecaller.truepay.UserRegistered"));
            boolean z = true;
            if (settingReceived != 1) {
                z = false;
            }
            return Boolean.valueOf(z);
        } catch (Exception e) {
            e.printStackTrace();
            AnalyticsUtil.reportError(e, "error", e.getMessage());
            return false;
        }
    }

    static boolean checkUpiRegisteredApp(Context context, String appPackage) {
        char c;
        switch (appPackage.hashCode()) {
            case 1170339061:
                if (appPackage.equals(PayUCheckoutProConstants.CP_GOOGLE_PAY_PACKAGE_NAME)) {
                    c = 0;
                    break;
                }
            default:
                c = 65535;
                break;
        }
        switch (c) {
            case 0:
                return isCompatibleWithGooglePay;
            default:
                return true;
        }
    }

    static HashSet<String> getSetOfPackageNamesSupportingUpi(Context context) {
        List<ResolveInfo> resolveInfoList = getListOfAppsWhichHandleDeepLink(context, "upi://pay");
        HashSet<String> upiPackagesSet = new HashSet<>();
        if (resolveInfoList != null && resolveInfoList.size() > 0) {
            for (ResolveInfo resolveInfo : resolveInfoList) {
                try {
                    upiPackagesSet.add(resolveInfo.activityInfo.packageName);
                } catch (Exception e) {
                    AnalyticsUtil.reportError(e, "critical", e.getLocalizedMessage());
                }
            }
        }
        if (upiPackagesSet.size() > 0 && !checkUpiRegisteredApp(context, PayUCheckoutProConstants.CP_GOOGLE_PAY_PACKAGE_NAME)) {
            upiPackagesSet.remove(PayUCheckoutProConstants.CP_GOOGLE_PAY_PACKAGE_NAME);
        }
        if (upiPackagesSet.size() > 0 && !checkUpiRegisteredApp(context, "com.truecaller")) {
            upiPackagesSet.remove("com.truecaller");
        }
        return upiPackagesSet;
    }

    static List<ResolveInfo> getListOfAppsWhichHandleDeepLink(Context context, String url) {
        Intent intent = new Intent();
        intent.setData(Uri.parse(url));
        return context.getPackageManager().queryIntentActivities(intent, 131072);
    }

    static String getAppNameOfResolveInfo(ResolveInfo resolveInfo, Context context) throws Exception {
        return getAppNameOfPackageName(resolveInfo.activityInfo.packageName, context);
    }

    static void startActivityForResult(String url, String packageName, Activity activity) {
        Intent i = new Intent("android.intent.action.VIEW");
        i.setData(Uri.parse(url));
        if (packageName != null && packageName.length() > 0) {
            i.setPackage(packageName);
        }
        if (url.startsWith("credpay")) {
            activity.startActivityForResult(i, 20);
        } else {
            activity.startActivityForResult(i, 99);
        }
    }

    static JSONObject getJSONFromIntentData(Intent data) {
        Bundle bundle;
        JSONObject jsonObject = new JSONObject();
        if (data != null && (bundle = data.getExtras()) != null) {
            Set<String> keys = bundle.keySet();
            for (String key : keys) {
                try {
                    jsonObject.put(key, bundle.get(key));
                } catch (JSONException e) {
                    AnalyticsUtil.reportError(e, "error:exception", e.getLocalizedMessage());
                }
            }
        }
        return jsonObject;
    }

    static String getBase64FromOtherAppsResource(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        try {
            ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, WorkQueueKt.BUFFER_CAPACITY);
            Resources resources = pm.getResourcesForApplication(applicationInfo);
            int appIconResId = applicationInfo.icon;
            return getBase64FromResource(resources, appIconResId);
        } catch (PackageManager.NameNotFoundException e) {
            AnalyticsUtil.reportError(e, "critical", e.getLocalizedMessage());
            e.printStackTrace();
            return null;
        }
    }

    static String getAppNameOfPackageName(String packageName, Context context) throws Exception {
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, WorkQueueKt.BUFFER_CAPACITY);
            int stringId = applicationInfo.labelRes;
            Resources resources = pm.getResourcesForApplication(applicationInfo);
            if (stringId == 0) {
                String appName = applicationInfo.nonLocalizedLabel.toString();
                return appName;
            }
            String appName2 = resources.getString(stringId);
            return appName2;
        } catch (Exception e) {
            AnalyticsUtil.reportError(e, "error:exception", e.getLocalizedMessage());
            e.printStackTrace();
            throw e;
        }
    }

    static String getBase64FromResource(Resources resources, int recourceId) {
        Drawable drawable;
        Bitmap bitmap = BitmapFactory.decodeResource(resources, recourceId);
        if (bitmap == null && (drawable = resources.getDrawable(recourceId)) != null) {
            if (drawable instanceof BitmapDrawable) {
                bitmap = ((BitmapDrawable) drawable).getBitmap();
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                drawable.draw(canvas);
            }
        }
        if (bitmap != null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            String base64 = "data:image/png;base64," + Base64.encodeToString(byteArray, 2);
            return base64;
        }
        return null;
    }

    static Object getJsonValue(String key, JSONObject jsonObject, Object defaultValue) {
        Object value = getJsonValue(key.split("\\."), jsonObject, 0);
        if (value != null) {
            return value;
        }
        return defaultValue;
    }

    private static Object getJsonValue(String[] keys, Object source, int keyIndex) {
        if (keyIndex == keys.length) {
            return source;
        }
        String key = keys[keyIndex];
        if (source instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) source;
            return getJsonValue(keys, jsonObject.opt(key), keyIndex + 1);
        }
        if (source instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) source;
            if (TextUtils.isDigitsOnly(key)) {
                int arrayIndex = Integer.parseInt(key);
                return getJsonValue(keys, jsonArray.opt(arrayIndex), keyIndex + 1);
            }
            return null;
        }
        return null;
    }

    static String getRandomString() {
        SecureRandom random = new SecureRandom();
        return new BigInteger(130, random).toString(32);
    }

    static String getFileFromInternal(Activity activity, String filename, String versionKey) throws Exception {
        String version = getLocalVersion(activity, versionKey).toString();
        FileInputStream fis = activity.openFileInput(getVersionedAssetName(version, filename));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        StringBuilder data = new StringBuilder();
        while (true) {
            String line = bufferedReader.readLine();
            if (line != null) {
                data.append(line);
            } else {
                bufferedReader.close();
                return decryptFile(data.toString());
            }
        }
    }

    static String decryptFile(String encryptedFile) {
        try {
            CryptLib crypto = new CryptLib();
            String shaKey = CryptLib.SHA256("", 32);
            String output = crypto.decrypt(encryptedFile, shaKey, "");
            return output;
        } catch (Exception e) {
            AnalyticsUtil.reportError(e, "error", "Unable to decrypt file");
            Logger.d("Unable to decrypt file, " + e.getMessage());
            return null;
        }
    }

    static String getVersionedAssetName(String version, String filename) {
        return version.replaceAll("\\.", "-") + "-" + filename;
    }

    static String getLocalVersion(Activity activity, String key) {
        String version = SharedPreferenceUtil.getValue(activity, key);
        if (version == null) {
            return getVersionFromJsonString("{\n  \"hash\" : \"9ee1052cde77d828ec522ab71d966d8d\",\n  \"magic_hash\": \"8082360e00c3117c97305f562403f237\"\n}\n", key);
        }
        return version;
    }

    static String getVersionFromJsonString(String versionString, String key) {
        try {
            JSONObject jsonObject = new JSONObject(versionString);
            if (key.equalsIgnoreCase("otpelf_version")) {
                return jsonObject.getString(com.payu.paymentparamhelper.PayuConstants.HASH);
            }
            if (key.equalsIgnoreCase("magic_version")) {
                return jsonObject.getString("magic_hash");
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    static void updateLocalVersion(Activity activity, String versionKey, String newVersion) {
        SharedPreferenceUtil.setValue(activity, versionKey, newVersion);
    }

    static boolean storeFileInInternal(Activity activity, String filename, String data) {
        try {
            FileOutputStream fos = activity.openFileOutput(filename, 0);
            fos.write(data.getBytes());
            fos.close();
            return true;
        } catch (Exception e) {
            AnalyticsUtil.reportError(e, "error", "Error in saving file: " + filename);
            Logger.e("Error in saving file: " + filename);
            return false;
        }
    }

    static void checkForLatestVersion(Context context, int sdkVersionCode) {
        if (CoreConfig.getInstance().isSDKUpdateAlertEnabled() && isMerchantAppDebuggable(context) && sdkVersionCode < CoreConfig.getInstance().getLatestSDKVersionCode()) {
            String updateSDKMsg = CoreConfig.getInstance().getUpdateSDKMsg();
            Toast.makeText(context, updateSDKMsg, 1).show();
        }
    }

    static int dpToPixels(Context context, int dp) {
        Resources r = context.getResources();
        int px = (int) TypedValue.applyDimension(1, dp, r.getDisplayMetrics());
        return px;
    }

    static int getDisplayWidth(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    static int getDisplayHeight(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }

    static HashMap<String, String> getMapFromJSONObject(JSONObject jsonObject) {
        HashMap<String, String> map = new HashMap<>();
        try {
            Iterator<?> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                String value = jsonObject.getString(key);
                map.put(key, value);
            }
        } catch (Exception e) {
            AnalyticsUtil.reportError(e, "error:exception", e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    static void setCompatibleWithGooglePay(boolean compatibleWithGooglePay) {
        isCompatibleWithGooglePay = compatibleWithGooglePay;
    }

    static String makeUrlEncodedPayload(JSONObject paymentData) throws JSONException {
        StringBuilder result = new StringBuilder();
        Iterator<String> keys = paymentData.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            String value = paymentData.getString(key);
            result.append(String.format("%s=%s&", key, Uri.encode(value)));
        }
        return result.deleteCharAt(result.length() - 1).toString();
    }

    static String installedApps(Context context) {
        StringBuilder appBuilder = new StringBuilder();
        try {
            PackageManager pm = context.getPackageManager();
            List<ApplicationInfo> appInfoList = pm.getInstalledApplications(0);
            for (ApplicationInfo applicationInfo : appInfoList) {
                if ((applicationInfo.flags & 1) == 0) {
                    if (appBuilder.length() != 0) {
                        appBuilder.append(",");
                    }
                    appBuilder.append(applicationInfo.packageName);
                }
            }
            return appBuilder.toString();
        } catch (Throwable th) {
            return "Apps not available";
        }
    }

    static String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), "android_id");
    }

    static String getDisplayResolution(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return String.format(Locale.ENGLISH, "%dx%dx%d", Integer.valueOf(displayMetrics.widthPixels), Integer.valueOf(displayMetrics.heightPixels), Integer.valueOf(displayMetrics.densityDpi));
    }

    String getDeviceUptime() {
        return String.valueOf(SystemClock.elapsedRealtime()) + "ms";
    }

    String getParentAppVersion(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            AnalyticsUtil.reportError(e, "error:exception", e.getMessage());
            return "Permission Disabled";
        }
    }

    String getAvailableMemory(Context context) {
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
        activityManager.getMemoryInfo(mi);
        return String.valueOf(mi.availMem / 1048576) + "MB";
    }

    String getTotalInternalStorage() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSizeLong();
        long totalBlocks = stat.getBlockCountLong();
        return String.valueOf(totalBlocks * blockSize);
    }

    String getBatteryLevel(Context context) {
        Intent batteryIntent = context.registerReceiver(null, new IntentFilter("android.intent.action.BATTERY_CHANGED"));
        if (batteryIntent != null) {
            int level = batteryIntent.getIntExtra(FirebaseAnalytics.Param.LEVEL, -1);
            int scale = batteryIntent.getIntExtra("scale", -1);
            return String.valueOf((level / scale) * 100.0f);
        }
        return "Unknown";
    }

    String getAccounts(Context context) {
        if (context.checkCallingOrSelfPermission("android.permission.GET_ACCOUNTS") == 0) {
            StringBuilder accountBuilder = new StringBuilder();
            AccountManager accountManager = (AccountManager) context.getSystemService("account");
            for (Account account : accountManager.getAccounts()) {
                accountBuilder.append(account.name);
                accountBuilder.append(",");
            }
            return accountBuilder.toString();
        }
        return PERMISSION_DISABLED;
    }

    String getScreenOffTimeout(Context context) {
        String screenOffTimeout = Settings.System.getString(context.getContentResolver(), "screen_off_timeout");
        return screenOffTimeout + "ms";
    }

    String getScreenBrightnessMode(Context context) {
        return Settings.System.getString(context.getContentResolver(), "screen_brightness_mode");
    }

    String getScreenBrightness(Context context) {
        return Settings.System.getString(context.getContentResolver(), "screen_brightness");
    }

    String getWallpaperID(Context context) {
        if (Build.VERSION.SDK_INT >= 24) {
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
            int systemWallpaperId = wallpaperManager.getWallpaperId(1);
            int lockWallpaperId = wallpaperManager.getWallpaperId(2);
            return String.format(Locale.ENGLISH, "%d-%d", Integer.valueOf(lockWallpaperId), Integer.valueOf(systemWallpaperId));
        }
        return PERMISSION_DISABLED;
    }

    String getRingtoneHash(Context context) {
        Uri defaultRingtoneUri = RingtoneManager.getActualDefaultRingtoneUri(context, 1);
        Ringtone ringtone = RingtoneManager.getRingtone(context, defaultRingtoneUri);
        return MD5Hash(ringtone.getTitle(context));
    }

    public static String MD5Hash(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger no = new BigInteger(1, messageDigest);
            String hashtext = no.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    String getSystemFontSize(Context context) {
        return String.valueOf(context.getResources().getConfiguration().fontScale);
    }

    private boolean isMocked(Context context, Location location) {
        return location.isFromMockProvider();
    }

    static boolean isNetworkRoaming(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
        if (telephonyManager != null) {
            return telephonyManager.isNetworkRoaming();
        }
        return false;
    }

    static String getCarrierOperatorName(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
        if (telephonyManager != null) {
            return telephonyManager.getNetworkOperatorName();
        }
        return PERMISSION_DISABLED;
    }

    static Map<String, String> getDeviceAttributes(Context context) {
        HashMap<String, String> attributes = new HashMap<>();
        if (context.checkCallingOrSelfPermission("android.permission.READ_PHONE_STATE") == 0) {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
            attributes.put("device_id", BaseConfig.getAdvertisingId(context));
            if (Build.VERSION.SDK_INT <= 28) {
                attributes.put("sim_serial_number", telephonyManager != null ? telephonyManager.getSimSerialNumber() : "null");
            } else {
                attributes.put("sim_serial_number", PERMISSION_DISABLED);
                attributes.put("build_unique_id", UUID.randomUUID().toString());
            }
        } else {
            attributes.put("device_id", PERMISSION_DISABLED);
            attributes.put("sim_serial_number", PERMISSION_DISABLED);
        }
        attributes.put("device_manufacturer", Build.MANUFACTURER);
        attributes.put("device_model", Build.MODEL);
        return attributes;
    }

    static String getWifiSSID(Context context) {
        if (context.checkCallingOrSelfPermission("android.permission.ACCESS_WIFI_STATE") == 0) {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService("wifi");
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            return wifiInfo.getSSID();
        }
        return PERMISSION_DISABLED;
    }

    static String buildSerial() {
        return Build.SERIAL;
    }

    static void fetchIP(final RzpJSONCallback jsonCallback) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                HttpsURLConnection urlConnection = null;
                try {
                    try {
                        try {
                            URL url = new URL("https://approvals-api.getsimpl.com/my-ip");
                            urlConnection = (HttpsURLConnection) url.openConnection();
                            urlConnection.setRequestMethod(PayuConstants.REQUEST_METHOD_GET);
                            urlConnection.setReadTimeout(150);
                            urlConnection.setConnectTimeout(OnScreenDisplay.View.ANIMATION_DURATION);
                            if (urlConnection.getResponseCode() == 200) {
                                JSONObject responseJson = BaseUtils.getResponseJson(urlConnection);
                                RzpJSONCallback.this.onResponse(responseJson);
                            } else {
                                RzpJSONCallback.this.onResponse(new JSONObject().put("error", "error"));
                            }
                            if (urlConnection == null) {
                                return;
                            }
                        } catch (Throwable th) {
                            if (0 != 0) {
                                urlConnection.disconnect();
                            }
                            throw th;
                        }
                    } catch (SocketTimeoutException e) {
                        RzpJSONCallback.this.onResponse(new JSONObject().put("error", "timeout"));
                        if (0 == 0) {
                            return;
                        }
                    } catch (Exception e2) {
                        AnalyticsUtil.reportError(e2, "warning", e2.getMessage());
                        if (0 == 0) {
                            return;
                        }
                    }
                    urlConnection.disconnect();
                } catch (Exception e3) {
                    AnalyticsUtil.reportError(e3, "warning", e3.getMessage());
                }
            }
        });
        thread.start();
    }

    static void getDeviceParamValues(final Context context, final RzpJSONCallback jsonCallback) {
        final JSONObject deviceParam = new JSONObject();
        try {
            fetchIP(new RzpJSONCallback() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        if (response.getString("ip") != null) {
                            BaseUtils.ipAddress = response.getString("ip");
                        }
                    } catch (JSONException e) {
                    }
                }
            });
            AdvertisingIdUtil.getId(context, new AdvertisingIdUtil.AdvertisingIdCallback() {
                @Override
                public void onResult(String advertisingId) {
                    try {
                        deviceParam.put("advertising_id", advertisingId);
                        deviceParam.put("is_roming", BaseUtils.isNetworkRoaming(context));
                        deviceParam.put("carrier_network", BaseUtils.getCarrierOperatorName(context));
                        deviceParam.put("carrier_id", "null");
                        Map<String, String> deviceParamMap = BaseUtils.getDeviceAttributes(context);
                        deviceParam.put("device_Id", deviceParamMap.get("device_Id"));
                        deviceParam.put("device_manufacturer", deviceParamMap.get("device_manufacturer"));
                        deviceParam.put("device_model", deviceParamMap.get("device_model"));
                        deviceParam.put("serial_number", BaseUtils.buildSerial());
                        deviceParam.put("ip_address", BaseUtils.ipAddress);
                        deviceParam.put("wifi_ssid", BaseUtils.getWifiSSID(context));
                        deviceParam.put("android_id", BaseUtils.getAndroidId(context));
                        deviceParam.put("safety_net basic_integrity", "true");
                        deviceParam.put("safety_net_cts_profile_match", "null");
                        jsonCallback.onResponse(deviceParam);
                    } catch (JSONException e) {
                        AnalyticsUtil.reportError(e, "warning", e.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            AnalyticsUtil.reportError(e, "warning", e.getMessage());
        }
    }

    static void getSignalStrength(Context context) {
        MyPhoneStateListener psListener = new MyPhoneStateListener();
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
        if (telephonyManager == null) {
            throw new AssertionError();
        }
        telephonyManager.listen(psListener, 256);
    }

    public static class MyPhoneStateListener extends PhoneStateListener {
        public int signalStrengthValue;

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            if (signalStrength.isGsm()) {
                if (signalStrength.getGsmSignalStrength() != 99) {
                    this.signalStrengthValue = (signalStrength.getGsmSignalStrength() * 2) - 113;
                    return;
                } else {
                    this.signalStrengthValue = signalStrength.getGsmSignalStrength();
                    return;
                }
            }
            this.signalStrengthValue = signalStrength.getCdmaDbm();
        }
    }

    public static JSONObject getResponseJson(HttpsURLConnection urlConnection) throws IOException, JSONException {
        BufferedReader in2 = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder response = new StringBuilder();
        while (true) {
            String line = in2.readLine();
            if (line != null) {
                response.append(line);
            } else {
                in2.close();
                return new JSONObject(response.toString());
            }
        }
    }

    static String getPaymentCancelledResponse(String paymentId) {
        try {
            JSONObject errorObject = new JSONObject();
            errorObject.put(com.instamojo.android.helpers.Constants.KEY_CODE, "BAD_REQUEST_ERROR");
            errorObject.put(PayuConstants.DESCRIPTION, "Payment processing cancelled by user");
            errorObject.put("source", "customer");
            errorObject.put("step", "payment_authentication");
            errorObject.put("reason", "payment_cancelled");
            if (paymentId != null && !paymentId.isEmpty()) {
                JSONObject jsonMetaData = new JSONObject();
                jsonMetaData.put("payment_id", paymentId);
                errorObject.put("metadata", jsonMetaData);
            }
            return new JSONObject().put("error", errorObject).toString();
        } catch (JSONException e) {
            AnalyticsUtil.reportError(e, "critical", e.getLocalizedMessage());
            return null;
        }
    }
}