]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blobdiff - app/src/main/java/com/stoutner/privacybrowser/dialogs/SslCertificateErrorDialog.kt
Switch the FragmentPagerAdapters to FragmentStateAdapters. https://redmine.stoutner...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / SslCertificateErrorDialog.kt
index 139e6576e78b7055bfac1fa4786a2706f8bead0a..aa0ae90856ef798a1eb75f9a0c411f6eacff2ca4 100644 (file)
@@ -1,32 +1,28 @@
 /*
- * Copyright © 2016-2021 Soren Stoutner <soren@stoutner.com>.
+ * Copyright 2016-2023 Soren Stoutner <soren@stoutner.com>.
  *
- * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
+ * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
  *
- * Privacy Browser is free software: you can redistribute it and/or modify
+ * Privacy Browser Android is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
- * Privacy Browser is distributed in the hope that it will be useful,
+ * Privacy Browser Android is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
+ * along with Privacy Browser Android.  If not, see <http://www.gnu.org/licenses/>.
  */
 
 package com.stoutner.privacybrowser.dialogs
 
-import android.annotation.SuppressLint
-import android.app.Activity
 import android.app.Dialog
 import android.content.DialogInterface
-import android.content.res.Configuration
 import android.net.Uri
 import android.net.http.SslError
-import android.os.AsyncTask
 import android.os.Bundle
 import android.text.SpannableStringBuilder
 import android.text.Spanned
@@ -40,11 +36,9 @@ import androidx.preference.PreferenceManager
 
 import com.stoutner.privacybrowser.R
 import com.stoutner.privacybrowser.activities.MainWebViewActivity
+import com.stoutner.privacybrowser.coroutines.GetHostIpAddressesCoroutine
 import com.stoutner.privacybrowser.views.NestedScrollWebView
 
-import java.lang.ref.WeakReference
-import java.net.InetAddress
-import java.net.UnknownHostException
 import java.text.DateFormat
 
 // Define the class constants.
@@ -62,8 +56,6 @@ private const val WEBVIEW_FRAGMENT_ID = "webview_fragment_id"
 
 class SslCertificateErrorDialog : DialogFragment() {
     companion object {
-        // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
-        @JvmStatic
         fun displayDialog(sslError: SslError, webViewFragmentId: Long): SslCertificateErrorDialog {
             // Get the various components of the SSL error message.
             val primaryErrorInt = sslError.primaryError
@@ -105,8 +97,6 @@ class SslCertificateErrorDialog : DialogFragment() {
         }
     }
 
-    // `@SuppressLint("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
-    @SuppressLint("InflateParams")
     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
         // Get the variables from the bundle.
         val primaryErrorInt = requireArguments().getInt(PRIMARY_ERROR_INT)
@@ -122,10 +112,10 @@ class SslCertificateErrorDialog : DialogFragment() {
         val webViewFragmentId = requireArguments().getLong(WEBVIEW_FRAGMENT_ID)
 
         // Get the current position of this WebView fragment.
-        val webViewPosition = MainWebViewActivity.webViewPagerAdapter.getPositionForId(webViewFragmentId)
+        val webViewPosition = MainWebViewActivity.webViewStateAdapter!!.getPositionForId(webViewFragmentId)
 
         // Get the WebView tab fragment.
-        val webViewTabFragment = MainWebViewActivity.webViewPagerAdapter.getPageFragment(webViewPosition)
+        val webViewTabFragment = MainWebViewActivity.webViewStateAdapter!!.getPageFragment(webViewPosition)
 
         // Get the fragment view.
         val fragmentView = webViewTabFragment.requireView()
@@ -139,23 +129,16 @@ class SslCertificateErrorDialog : DialogFragment() {
         // Use an alert dialog builder to create the alert dialog.
         val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
 
-        // Get the current theme status.
-        val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
-
-        // Set the icon according to the theme.
-        if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
-            dialogBuilder.setIcon(R.drawable.ssl_certificate_enabled_day)
-        } else {
-            dialogBuilder.setIcon(R.drawable.ssl_certificate_enabled_night)
-        }
+        // Set the icon.
+        dialogBuilder.setIcon(R.drawable.ssl_certificate)
 
         // Set the title.
         dialogBuilder.setTitle(R.string.ssl_certificate_error)
 
-        // Set the view.  The parent view is null because it will be assigned by the alert dialog.
-        dialogBuilder.setView(layoutInflater.inflate(R.layout.ssl_certificate_error, null))
+        // Set the view.
+        dialogBuilder.setView(R.layout.ssl_certificate_error)
 
-        // Set a listener on the cancel button.
+        // Set the cancel button listener.
         dialogBuilder.setNegativeButton(R.string.cancel) { _: DialogInterface?, _: Int ->
             // Check to make sure the SSL error handler is not null.  This might happen if multiple dialogs are displayed at once.
             if (sslErrorHandler != null) {
@@ -167,7 +150,7 @@ class SslCertificateErrorDialog : DialogFragment() {
             }
         }
 
-        // Set a listener on the proceed button.
+        // Set the proceed button listener.
         dialogBuilder.setPositiveButton(R.string.proceed) { _: DialogInterface?, _: Int ->
             // Check to make sure the SSL error handler is not null.  This might happen if multiple dialogs are displayed at once.
             if (sslErrorHandler != null) {
@@ -183,7 +166,7 @@ class SslCertificateErrorDialog : DialogFragment() {
         val alertDialog = dialogBuilder.create()
 
         // Get a handle for the shared preferences.
-        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
+        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
 
         // Get the screenshot preference.
         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
@@ -197,15 +180,13 @@ class SslCertificateErrorDialog : DialogFragment() {
         // Get a URI for the URL with errors.
         val uriWithErrors = Uri.parse(urlWithErrors)
 
-        // Get the IP addresses for the URI.
-        GetIpAddresses(requireActivity(), alertDialog).execute(uriWithErrors.host)
-
         // The alert dialog must be shown before the contents can be modified.
         alertDialog.show()
 
         // Get handles for the views.
         val primaryErrorTextView = alertDialog.findViewById<TextView>(R.id.primary_error)!!
         val urlTextView = alertDialog.findViewById<TextView>(R.id.url)!!
+        val ipAddressesTextView = alertDialog.findViewById<TextView>(R.id.ip_addresses)!!
         val issuedToCNameTextView = alertDialog.findViewById<TextView>(R.id.issued_to_cname)!!
         val issuedToONameTextView = alertDialog.findViewById<TextView>(R.id.issued_to_oname)!!
         val issuedToUNameTextView = alertDialog.findViewById<TextView>(R.id.issued_to_uname)!!
@@ -217,13 +198,20 @@ class SslCertificateErrorDialog : DialogFragment() {
         val startDateTextView = alertDialog.findViewById<TextView>(R.id.start_date)!!
         val endDateTextView = alertDialog.findViewById<TextView>(R.id.end_date)!!
 
+        // Define the color spans.
+        val blueColorSpan = ForegroundColorSpan(requireContext().getColor(R.color.alt_blue_text))
+        val redColorSpan = ForegroundColorSpan(requireContext().getColor(R.color.red_text))
+
+        // Get the IP Addresses for the URI.
+        GetHostIpAddressesCoroutine.getAddresses(uriWithErrors.host!!, getString(R.string.ip_addresses), blueColorSpan, ipAddressesTextView)
+
         // Setup the common strings.
-        val urlLabel = getString(R.string.url_label) + "  "
-        val cNameLabel = getString(R.string.common_name) + "  "
-        val oNameLabel = getString(R.string.organization) + "  "
-        val uNameLabel = getString(R.string.organizational_unit) + "  "
-        val startDateLabel = getString(R.string.start_date) + "  "
-        val endDateLabel = getString(R.string.end_date) + "  "
+        val urlLabel = getString(R.string.url_label)
+        val cNameLabel = getString(R.string.common_name)
+        val oNameLabel = getString(R.string.organization)
+        val uNameLabel = getString(R.string.organizational_unit)
+        val startDateLabel = getString(R.string.start_date)
+        val endDateLabel = getString(R.string.end_date)
 
         // Create a spannable string builder for each text view that needs multiple colors of text.
         val urlStringBuilder = SpannableStringBuilder(urlLabel + urlWithErrors)
@@ -236,23 +224,6 @@ class SslCertificateErrorDialog : DialogFragment() {
         val startDateStringBuilder = SpannableStringBuilder(startDateLabel + startDate)
         val endDateStringBuilder = SpannableStringBuilder(endDateLabel + endDate)
 
-        // Define the color spans.
-        val blueColorSpan: ForegroundColorSpan
-        val redColorSpan: ForegroundColorSpan
-
-        // Set the color spans according to the theme.  The deprecated `getColor()` must be used until the minimum API >= 23.
-        if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
-            @Suppress("DEPRECATION")
-            blueColorSpan = ForegroundColorSpan(resources.getColor(R.color.blue_700))
-            @Suppress("DEPRECATION")
-            redColorSpan = ForegroundColorSpan(resources.getColor(R.color.red_a700))
-        } else {
-            @Suppress("DEPRECATION")
-            blueColorSpan = ForegroundColorSpan(resources.getColor(R.color.violet_700))
-            @Suppress("DEPRECATION")
-            redColorSpan = ForegroundColorSpan(resources.getColor(R.color.red_900))
-        }
-
         // Setup the spans to display the certificate information in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
         urlStringBuilder.setSpan(blueColorSpan, urlLabel.length, urlStringBuilder.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
         issuedToCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length, issuedToCNameStringBuilder.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
@@ -279,14 +250,8 @@ class SslCertificateErrorDialog : DialogFragment() {
             }
 
             SslError.SSL_UNTRUSTED -> {
-                // Change the issued by text view text to red.  The deprecated `getColor()` must be used until the minimum API >= 23.
-                if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
-                    @Suppress("DEPRECATION")
-                    issuedByTextView.setTextColor(resources.getColor(R.color.red_a700))
-                } else {
-                    @Suppress("DEPRECATION")
-                    issuedByTextView.setTextColor(resources.getColor(R.color.red_900))
-                }
+                // Change the issued by text view text to red.
+                issuedByTextView.setTextColor(requireContext().getColor(R.color.red_text))
 
                 // Change the issued by span color to red.
                 issuedByCNameStringBuilder.setSpan(redColorSpan, cNameLabel.length, issuedByCNameStringBuilder.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
@@ -298,14 +263,8 @@ class SslCertificateErrorDialog : DialogFragment() {
             }
 
             SslError.SSL_DATE_INVALID -> {
-                // Change the valid dates text view text to red.  The deprecated `getColor()` must be used until the minimum API >= 23.
-                if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
-                    @Suppress("DEPRECATION")
-                    validDatesTextView.setTextColor(resources.getColor(R.color.red_a700))
-                } else {
-                    @Suppress("DEPRECATION")
-                    validDatesTextView.setTextColor(resources.getColor(R.color.red_900))
-                }
+                // Change the valid dates text view text to red.
+                validDatesTextView.setTextColor(requireContext().getColor(R.color.red_text))
 
                 // Change the date span colors to red.
                 startDateStringBuilder.setSpan(redColorSpan, startDateLabel.length, startDateStringBuilder.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
@@ -336,7 +295,6 @@ class SslCertificateErrorDialog : DialogFragment() {
                 primaryErrorString = getString(R.string.invalid_certificate)
         }
 
-
         // Display the strings.
         primaryErrorTextView.text = primaryErrorString
         urlTextView.text = urlStringBuilder
@@ -352,90 +310,4 @@ class SslCertificateErrorDialog : DialogFragment() {
         // Return the alert dialog.
         return alertDialog
     }
-
-    // This must run asynchronously because it involves a network request.  `String` declares the parameters.  `Void` does not declare progress units.  `SpannableStringBuilder` contains the results.
-    private class GetIpAddresses constructor(activity: Activity, alertDialog: AlertDialog) : AsyncTask<String, Void?, SpannableStringBuilder>() {
-        // Define the weak references.
-        private val activityWeakReference: WeakReference<Activity> = WeakReference(activity)
-        private val alertDialogWeakReference: WeakReference<AlertDialog> = WeakReference(alertDialog)
-
-        override fun doInBackground(vararg domainName: String): SpannableStringBuilder {
-            // Get handles for the activity and the alert dialog.
-            val activity = activityWeakReference.get()
-            val alertDialog = alertDialogWeakReference.get()
-
-            // Abort if the activity or the dialog is gone.
-            if (activity == null || activity.isFinishing || alertDialog == null) {
-                return SpannableStringBuilder()
-            }
-
-            // Initialize an IP address string builder.
-            val ipAddresses = StringBuilder()
-
-            // Get an array with the IP addresses for the host.
-            try {
-                // Get an array with all the IP addresses for the domain.
-                val inetAddressesArray = InetAddress.getAllByName(domainName[0])
-
-                // Add each IP address to the string builder.
-                for (inetAddress in inetAddressesArray) {
-                    // Check to see if this is not the first IP address.
-                    if (ipAddresses.isNotEmpty()) {
-                        // Add a line break to the string builder first.
-                        ipAddresses.append("\n")
-                    }
-
-                    // Add the IP Address to the string builder.
-                    ipAddresses.append(inetAddress.hostAddress)
-                }
-            } catch (exception: UnknownHostException) {
-                // Do nothing.
-            }
-
-            // Set the label.
-            val ipAddressesLabel = activity.getString(R.string.ip_addresses) + "  "
-
-            // Create a spannable string builder.
-            val ipAddressesStringBuilder = SpannableStringBuilder(ipAddressesLabel + ipAddresses)
-
-            // Create a blue foreground color span.
-            val blueColorSpan: ForegroundColorSpan
-
-            // Get the current theme status.
-            val currentThemeStatus = activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
-
-            // Set the blue color span according to the theme.  The deprecated `getColor()` must be used until the minimum API >= 23.
-            blueColorSpan = if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
-                @Suppress("DEPRECATION")
-                ForegroundColorSpan(activity.resources.getColor(R.color.blue_700))
-            } else {
-                @Suppress("DEPRECATION")
-                ForegroundColorSpan(activity.resources.getColor(R.color.violet_500))
-            }
-
-            // Set the string builder to display the certificate information in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
-            ipAddressesStringBuilder.setSpan(blueColorSpan, ipAddressesLabel.length, ipAddressesStringBuilder.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
-
-            // Return the formatted string.
-            return ipAddressesStringBuilder
-        }
-
-        // `onPostExecute()` operates on the UI thread.
-        override fun onPostExecute(ipAddresses: SpannableStringBuilder) {
-            // Get handles for the activity and the alert dialog.
-            val activity = activityWeakReference.get()
-            val alertDialog = alertDialogWeakReference.get()
-
-            // Abort if the activity or the alert dialog is gone.
-            if (activity == null || activity.isFinishing || alertDialog == null) {
-                return
-            }
-
-            // Get a handle for the IP addresses text view.
-            val ipAddressesTextView = alertDialog.findViewById<TextView>(R.id.ip_addresses)!!
-
-            // Populate the IP addresses text view.
-            ipAddressesTextView.text = ipAddresses
-        }
-    }
-}
\ No newline at end of file
+}