Use WebView's new built-in dark theme. https://redmine.stoutner.com/issues/366
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / ViewSslCertificateDialog.java
1 /*
2  * Copyright © 2016-2020 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs;
21
22 import android.annotation.SuppressLint;
23 import android.app.Activity;
24 import android.app.Dialog;
25 import android.content.Context;
26 import android.content.SharedPreferences;
27 import android.content.res.Configuration;
28 import android.graphics.drawable.BitmapDrawable;
29 import android.graphics.drawable.Drawable;
30 import android.net.Uri;
31 import android.net.http.SslCertificate;
32 import android.os.Bundle;
33 import android.text.SpannableStringBuilder;
34 import android.text.Spanned;
35 import android.text.style.ForegroundColorSpan;
36 import android.view.LayoutInflater;
37 import android.view.View;
38 import android.view.WindowManager;
39 import android.widget.TextView;
40
41 import androidx.annotation.NonNull;
42 import androidx.appcompat.app.AlertDialog;
43 import androidx.fragment.app.DialogFragment;
44 import androidx.preference.PreferenceManager;
45
46 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
47 import com.stoutner.privacybrowser.R;
48 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
49 import com.stoutner.privacybrowser.views.NestedScrollWebView;
50
51 import java.text.DateFormat;
52 import java.util.Calendar;
53 import java.util.Date;
54
55 public class ViewSslCertificateDialog extends DialogFragment {
56     public static ViewSslCertificateDialog displayDialog(long webViewFragmentId) {
57         // Create an arguments bundle.
58         Bundle argumentsBundle = new Bundle();
59
60         // Store the WebView fragment ID in the bundle.
61         argumentsBundle.putLong("webview_fragment_id", webViewFragmentId);
62
63         // Create a new instance of the dialog.
64         ViewSslCertificateDialog viewSslCertificateDialog = new ViewSslCertificateDialog();
65
66         // Add the bundle to the dialog.
67         viewSslCertificateDialog.setArguments(argumentsBundle);
68
69         // Return the new dialog.
70         return viewSslCertificateDialog;
71     }
72
73     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
74     @SuppressLint("InflateParams")
75     @Override
76     @NonNull
77     public Dialog onCreateDialog(Bundle savedInstanceState) {
78         // Get a handle for the activity and the context.
79         Activity activity = requireActivity();
80         Context context = requireContext();
81
82         // Get the activity's layout inflater.
83         LayoutInflater layoutInflater = activity.getLayoutInflater();
84
85         // Get the arguments.
86         Bundle arguments = getArguments();
87
88         // Remove the incorrect lint warning below that the arguments might be null.
89         assert arguments != null;
90
91         // Get the current position of this WebView fragment.
92         int webViewPosition = MainWebViewActivity.webViewPagerAdapter.getPositionForId(arguments.getLong("webview_fragment_id"));
93
94         // Get the WebView tab fragment.
95         WebViewTabFragment webViewTabFragment = MainWebViewActivity.webViewPagerAdapter.getPageFragment(webViewPosition);
96
97         // Get the fragment view.
98         View fragmentView = webViewTabFragment.getView();
99
100         // Remove the incorrect lint warning below that the fragment view might be null.
101         assert fragmentView != null;
102
103         // Get a handle for the current WebView.
104         NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
105
106
107         // Use a builder to create the alert dialog.
108         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialog);
109
110         // Create a drawable version of the favorite icon.
111         Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), nestedScrollWebView.getFavoriteOrDefaultIcon());
112
113         // Set the icon.
114         dialogBuilder.setIcon(favoriteIconDrawable);
115
116         // Set the close button listener.  Using `null` as the listener closes the dialog without doing anything else.
117         dialogBuilder.setNegativeButton(R.string.close, null);
118
119         // Get the SSL certificate.
120         SslCertificate sslCertificate = nestedScrollWebView.getCertificate();
121
122         // Get a handle for the shared preferences.
123         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
124
125         // Get the screenshot preference.
126         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
127
128         // Check to see if the website is encrypted.
129         if (sslCertificate == null) {  // The website is not encrypted.
130             // Set the title.
131             dialogBuilder.setTitle(R.string.unencrypted_website);
132
133             // Set the Layout.  The parent view is `null` because it will be assigned by the alert dialog.
134             dialogBuilder.setView(layoutInflater.inflate(R.layout.unencrypted_website_dialog, null));
135
136             // Create an alert dialog from the alert dialog builder.
137             final AlertDialog alertDialog = dialogBuilder.create();
138
139             // Disable screenshots if not allowed.
140             if (!allowScreenshots) {
141                 // Remove the warning below that `getWindow()` might be null.
142                 assert alertDialog.getWindow() != null;
143
144                 // Disable screenshots.
145                 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
146             }
147
148             // `onCreateDialog` requires the return of an `AlertDialog`.
149             return alertDialog;
150         } else {  // Display the SSL certificate information
151             // Set the title.
152             dialogBuilder.setTitle(R.string.ssl_certificate);
153
154             // Set the layout.  The parent view is `null` because it will be assigned by the alert dialog.
155             dialogBuilder.setView(layoutInflater.inflate(R.layout.view_ssl_certificate_dialog, null));
156
157             // Create an alert dialog from the builder.
158             final AlertDialog alertDialog = dialogBuilder.create();
159
160             // Disable screenshots if not allowed.
161             if (!allowScreenshots) {
162                 // Remove the warning below that `getWindow()` might be null.
163                 assert alertDialog.getWindow() != null;
164
165                 // Disable screenshots.
166                 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
167             }
168
169             // The alert dialog must be shown before items in the layout can be modified.
170             alertDialog.show();
171
172             // Get handles for the text views.
173             TextView domainTextView = alertDialog.findViewById(R.id.domain);
174             TextView ipAddressesTextView = alertDialog.findViewById(R.id.ip_addresses);
175             TextView issuedToCNameTextView = alertDialog.findViewById(R.id.issued_to_cname);
176             TextView issuedToONameTextView = alertDialog.findViewById(R.id.issued_to_oname);
177             TextView issuedToUNameTextView = alertDialog.findViewById(R.id.issued_to_uname);
178             TextView issuedByCNameTextView = alertDialog.findViewById(R.id.issued_by_cname);
179             TextView issuedByONameTextView = alertDialog.findViewById(R.id.issued_by_oname);
180             TextView issuedByUNameTextView = alertDialog.findViewById(R.id.issued_by_uname);
181             TextView startDateTextView = alertDialog.findViewById(R.id.start_date);
182             TextView endDateTextView = alertDialog.findViewById(R.id.end_date);
183
184             // Remove the incorrect warning that the views might be null.
185             assert domainTextView != null;
186             assert ipAddressesTextView != null;
187             assert issuedToCNameTextView != null;
188             assert issuedToONameTextView != null;
189             assert issuedToUNameTextView != null;
190             assert issuedByCNameTextView != null;
191             assert issuedByONameTextView != null;
192             assert issuedByUNameTextView != null;
193             assert startDateTextView != null;
194             assert endDateTextView != null;
195
196             // Setup the labels.
197             String domainLabel = getString(R.string.domain_label) + "  ";
198             String ipAddressesLabel = getString(R.string.ip_addresses) + "  ";
199             String cNameLabel = getString(R.string.common_name) + "  ";
200             String oNameLabel = getString(R.string.organization) + "  ";
201             String uNameLabel = getString(R.string.organizational_unit) + "  ";
202             String startDateLabel = getString(R.string.start_date) + "  ";
203             String endDateLabel = getString(R.string.end_date) + "  ";
204
205             // Convert the formatted URL string to a URI.
206             Uri uri = Uri.parse(nestedScrollWebView.getUrl());
207
208             // Extract the domain name from the URI.
209             String domainString = uri.getHost();
210
211             // Get the strings from the SSL certificate.
212             String issuedToCName = sslCertificate.getIssuedTo().getCName();
213             String issuedToOName = sslCertificate.getIssuedTo().getOName();
214             String issuedToUName = sslCertificate.getIssuedTo().getUName();
215             String issuedByCName = sslCertificate.getIssuedBy().getCName();
216             String issuedByOName = sslCertificate.getIssuedBy().getOName();
217             String issuedByUName = sslCertificate.getIssuedBy().getUName();
218             Date startDate = sslCertificate.getValidNotBeforeDate();
219             Date endDate = sslCertificate.getValidNotAfterDate();
220
221             // Create spannable string builders for each text view that needs multiple colors of text.
222             SpannableStringBuilder domainStringBuilder = new SpannableStringBuilder(domainLabel + domainString);
223             SpannableStringBuilder ipAddressesStringBuilder = new SpannableStringBuilder(ipAddressesLabel + nestedScrollWebView.getCurrentIpAddresses());
224             SpannableStringBuilder issuedToCNameStringBuilder = new SpannableStringBuilder(cNameLabel + issuedToCName);
225             SpannableStringBuilder issuedToONameStringBuilder = new SpannableStringBuilder(oNameLabel + issuedToOName);
226             SpannableStringBuilder issuedToUNameStringBuilder = new SpannableStringBuilder(uNameLabel + issuedToUName);
227             SpannableStringBuilder issuedByCNameStringBuilder = new SpannableStringBuilder(cNameLabel + issuedByCName);
228             SpannableStringBuilder issuedByONameStringBuilder = new SpannableStringBuilder(oNameLabel + issuedByOName);
229             SpannableStringBuilder issuedByUNameStringBuilder = new SpannableStringBuilder(uNameLabel + issuedByUName);
230             SpannableStringBuilder startDateStringBuilder = new SpannableStringBuilder(startDateLabel + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(startDate));
231             SpannableStringBuilder endDateStringBuilder = new SpannableStringBuilder(endDateLabel + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(endDate));
232
233             // Define the color spans.
234             ForegroundColorSpan blueColorSpan;
235             ForegroundColorSpan redColorSpan;
236
237             // Get the current theme status.
238             int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
239
240             // Set the color spans according to the theme.  The deprecated `getResources()` must be used until the minimum API >= 23.
241             if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
242                 blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.violet_500));
243                 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_900));
244             } else {
245                 blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_700));
246                 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
247             }
248
249             // Remove the incorrect lint error that `.equals` might produce a NullPointerException.
250             assert domainString != null;
251
252             // Formet the domain string and issued to CName colors.
253             if (domainString.equals(issuedToCName)) {  // `domainString` and `issuedToCName` match.
254                 // Set the strings to be blue.
255                 domainStringBuilder.setSpan(blueColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
256                 issuedToCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
257             } else if(issuedToCName.startsWith("*.")){  // `issuedToCName` begins with a wildcard.
258                 // Remove the initial `*.`.
259                 String baseCertificateDomain = issuedToCName.substring(2);
260
261                 // Setup a copy of `domainString` to test subdomains.
262                 String domainStringSubdomain = domainString;
263
264                 // Initialize `domainNamesMatch`.
265                 boolean domainNamesMatch = false;
266
267                 // Check all the subdomains in `domainStringSubdomain` against `baseCertificateDomain`.
268                 while (!domainNamesMatch && domainStringSubdomain.contains(".")) {  // Stop checking if we know that `domainNamesMatch` is `true` or if we run out of  `.`.
269                     // Test the `domainStringSubdomain` against `baseCertificateDomain`.
270                     if (domainStringSubdomain.equals(baseCertificateDomain)) {
271                         domainNamesMatch = true;
272                     }
273
274                     // Strip out the lowest subdomain of `certificateCommonNameSubdomain`.
275                     domainStringSubdomain = domainStringSubdomain.substring(domainStringSubdomain.indexOf(".") + 1);
276                 }
277
278                 // Format the domain and issued to Common Name according to `domainNamesMatch`.
279                 if (domainNamesMatch) {  // `domainString` is a subdomain of the wildcard `issuedToCNameString`.
280                     // Set the strings to be blue.
281                     domainStringBuilder.setSpan(blueColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
282                     issuedToCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
283                 } else {  // `domainString` is not a subdomain of the wildcard `issuedToCNameString`.
284                     // Set the string to be red.
285                     domainStringBuilder.setSpan(redColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
286                     issuedToCNameStringBuilder.setSpan(redColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
287                 }
288             } else {  // The strings do not match and `issuedToCNameString` does not begin with a wildcard.
289                 // Set the strings to be red.
290                 domainStringBuilder.setSpan(redColorSpan, domainLabel.length(), domainStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
291                 issuedToCNameStringBuilder.setSpan(redColorSpan, cNameLabel.length(), issuedToCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
292             }
293
294             // Set the IP addresses, issued to, and issued by spans to display the certificate information in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
295             ipAddressesStringBuilder.setSpan(blueColorSpan, ipAddressesLabel.length(), ipAddressesStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
296             issuedToONameStringBuilder.setSpan(blueColorSpan, oNameLabel.length(), issuedToONameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
297             issuedToUNameStringBuilder.setSpan(blueColorSpan, uNameLabel.length(), issuedToUNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
298             issuedByCNameStringBuilder.setSpan(blueColorSpan, cNameLabel.length(), issuedByCNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
299             issuedByONameStringBuilder.setSpan(blueColorSpan, oNameLabel.length(), issuedByONameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
300             issuedByUNameStringBuilder.setSpan(blueColorSpan, uNameLabel.length(), issuedByUNameStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
301
302             // Get the current date.
303             Date currentDate = Calendar.getInstance().getTime();
304
305             //  Format the start date color.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
306             if (startDate.after(currentDate)) {  // The certificate start date is in the future.
307                 startDateStringBuilder.setSpan(redColorSpan, startDateLabel.length(), startDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
308             } else {  // The certificate start date is in the past.
309                 startDateStringBuilder.setSpan(blueColorSpan, startDateLabel.length(), startDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
310             }
311
312             // Format the end date color.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
313             if (endDate.before(currentDate)) {  // The certificate end date is in the past.
314                 endDateStringBuilder.setSpan(redColorSpan, endDateLabel.length(), endDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
315             } else {  // The certificate end date is in the future.
316                 endDateStringBuilder.setSpan(blueColorSpan, endDateLabel.length(), endDateStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
317             }
318
319             // Display the strings.
320             domainTextView.setText(domainStringBuilder);
321             ipAddressesTextView.setText(ipAddressesStringBuilder);
322             issuedToCNameTextView.setText(issuedToCNameStringBuilder);
323             issuedToONameTextView.setText(issuedToONameStringBuilder);
324             issuedToUNameTextView.setText(issuedToUNameStringBuilder);
325             issuedByCNameTextView.setText(issuedByCNameStringBuilder);
326             issuedByONameTextView.setText(issuedByONameStringBuilder);
327             issuedByUNameTextView.setText(issuedByUNameStringBuilder);
328             startDateTextView.setText(startDateStringBuilder);
329             endDateTextView.setText(endDateStringBuilder);
330
331             // `onCreateDialog` requires the return of an alert dialog.
332             return alertDialog;
333         }
334     }
335 }