]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/ViewSourceActivity.kt
759b79c0fb00ebbbe91fc20bb21e002392c4bfb7
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / ViewSourceActivity.kt
1 /*
2  * Copyright © 2017-2021 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.activities
21
22 import android.content.res.Configuration
23 import android.os.Build
24 import android.os.Bundle
25 import android.text.SpannableStringBuilder
26 import android.text.Spanned
27 import android.text.style.ForegroundColorSpan
28 import android.util.TypedValue
29 import android.view.KeyEvent
30 import android.view.Menu
31 import android.view.MenuItem
32 import android.view.View
33 import android.view.View.OnFocusChangeListener
34 import android.view.WindowManager
35 import android.view.inputmethod.InputMethodManager
36 import android.widget.EditText
37 import android.widget.ProgressBar
38 import android.widget.TextView
39
40 import androidx.appcompat.app.ActionBar
41 import androidx.appcompat.app.AppCompatActivity
42 import androidx.appcompat.widget.Toolbar
43 import androidx.core.app.NavUtils
44 import androidx.fragment.app.DialogFragment
45 import androidx.lifecycle.ViewModelProvider
46 import androidx.preference.PreferenceManager
47 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
48
49 import com.google.android.material.snackbar.Snackbar
50
51 import com.stoutner.privacybrowser.R
52 import com.stoutner.privacybrowser.dialogs.AboutViewSourceDialog
53 import com.stoutner.privacybrowser.dialogs.UntrustedSslCertificateDialog
54 import com.stoutner.privacybrowser.dialogs.UntrustedSslCertificateDialog.UntrustedSslCertificateListener
55 import com.stoutner.privacybrowser.helpers.ProxyHelper
56 import com.stoutner.privacybrowser.viewmodelfactories.WebViewSourceFactory
57 import com.stoutner.privacybrowser.viewmodels.WebViewSource
58
59 import java.util.Locale
60
61 // Declare the public constants.
62 const val CURRENT_URL = "current_url"
63 const val USER_AGENT = "user_agent"
64
65 class ViewSourceActivity: AppCompatActivity(), UntrustedSslCertificateListener {
66     // Declare the class variables.
67     private lateinit var initialGrayColorSpan: ForegroundColorSpan
68     private lateinit var finalGrayColorSpan: ForegroundColorSpan
69     private lateinit var redColorSpan: ForegroundColorSpan
70     private lateinit var webViewSource: WebViewSource
71
72     // Declare the class views.
73     private lateinit var urlEditText: EditText
74     private lateinit var requestHeadersTitleTextView: TextView
75     private lateinit var requestHeadersTextView: TextView
76     private lateinit var responseMessageTitleTextView: TextView
77     private lateinit var responseMessageTextView: TextView
78     private lateinit var responseHeadersTitleTextView: TextView
79     private lateinit var responseBodyTitleTextView: TextView
80
81     override fun onCreate(savedInstanceState: Bundle?) {
82         // Get a handle for the shared preferences.
83         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
84
85         // Get the preferences.
86         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
87         val bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
88
89         // Disable screenshots if not allowed.
90         if (!allowScreenshots) {
91             window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
92         }
93
94         // Set the theme.
95         setTheme(R.style.PrivacyBrowser)
96
97         // Run the default commands.
98         super.onCreate(savedInstanceState)
99
100         // Get the launching intent
101         val intent = intent
102
103         // Get the information from the intent.
104         val currentUrl = intent.getStringExtra(CURRENT_URL)!!
105         val userAgent = intent.getStringExtra(USER_AGENT)!!
106
107         // Set the content view.
108         if (bottomAppBar) {
109             setContentView(R.layout.view_source_bottom_appbar)
110         } else {
111             setContentView(R.layout.view_source_top_appbar)
112         }
113
114         // Get a handle for the toolbar.
115         val toolbar = findViewById<Toolbar>(R.id.view_source_toolbar)
116
117         // Set the support action bar.
118         setSupportActionBar(toolbar)
119
120         // Get a handle for the action bar.
121         val actionBar = supportActionBar!!
122
123         // Add the custom layout to the action bar.
124         actionBar.setCustomView(R.layout.view_source_app_bar)
125
126         // Instruct the action bar to display a custom layout.
127         actionBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
128
129         // Get handles for the views.
130         urlEditText = findViewById(R.id.url_edittext)
131         val progressBar = findViewById<ProgressBar>(R.id.progress_bar)
132         val swipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.view_source_swiperefreshlayout)
133         requestHeadersTitleTextView = findViewById(R.id.request_headers_title_textview)
134         requestHeadersTextView = findViewById(R.id.request_headers_textview)
135         responseMessageTitleTextView = findViewById(R.id.response_message_title_textview)
136         responseMessageTextView = findViewById(R.id.response_message_textview)
137         responseHeadersTitleTextView = findViewById(R.id.response_headers_title_textivew)
138         val responseHeadersTextView = findViewById<TextView>(R.id.response_headers_textview)
139         responseBodyTitleTextView = findViewById(R.id.response_body_title_textview)
140         val responseBodyTextView = findViewById<TextView>(R.id.response_body_textview)
141
142         // Populate the URL text box.
143         urlEditText.setText(currentUrl)
144
145         // Initialize the gray foreground color spans for highlighting the URLs.  The deprecated `getColor()` must be used until the minimum API >= 23.
146         @Suppress("DEPRECATION")
147         initialGrayColorSpan = ForegroundColorSpan(resources.getColor(R.color.gray_500))
148         @Suppress("DEPRECATION")
149         finalGrayColorSpan = ForegroundColorSpan(resources.getColor(R.color.gray_500))
150
151         // Get the current theme status.
152         val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
153
154         // Set the red color span according to the theme.  The deprecated `getColor()` must be used until the minimum API >= 23.
155         redColorSpan = if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
156             @Suppress("DEPRECATION")
157             ForegroundColorSpan(resources.getColor(R.color.red_a700))
158         } else {
159             @Suppress("DEPRECATION")
160             ForegroundColorSpan(resources.getColor(R.color.red_900))
161         }
162
163         // Apply text highlighting to the URL.
164         highlightUrlText()
165
166         // Get a handle for the input method manager, which is used to hide the keyboard.
167         val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
168
169         // Remove the formatting from the URL when the user is editing the text.
170         urlEditText.onFocusChangeListener = OnFocusChangeListener { _: View?, hasFocus: Boolean ->
171             if (hasFocus) {  // The user is editing the URL text box.
172                 // Remove the highlighting.
173                 urlEditText.text.removeSpan(redColorSpan)
174                 urlEditText.text.removeSpan(initialGrayColorSpan)
175                 urlEditText.text.removeSpan(finalGrayColorSpan)
176             } else {  // The user has stopped editing the URL text box.
177                 // Hide the soft keyboard.
178                 inputMethodManager.hideSoftInputFromWindow(urlEditText.windowToken, 0)
179
180                 // Move to the beginning of the string.
181                 urlEditText.setSelection(0)
182
183                 // Reapply the highlighting.
184                 highlightUrlText()
185             }
186         }
187
188         // Set the refresh color scheme according to the theme.
189         swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
190
191         // Initialize a color background typed value.
192         val colorBackgroundTypedValue = TypedValue()
193
194         // Get the color background from the theme.
195         theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
196
197         // Get the color background int from the typed value.
198         val colorBackgroundInt = colorBackgroundTypedValue.data
199
200         // Set the swipe refresh background color.
201         swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
202
203         // Populate the locale string.
204         val localeString = if (Build.VERSION.SDK_INT >= 24) {  // SDK >= 24 has a list of locales.
205             // Get the list of locales.
206             val localeList = resources.configuration.locales
207
208             // Initialize a string builder to extract the locales from the list.
209             val localesStringBuilder = StringBuilder()
210
211             // Initialize a `q` value, which is used by `WebView` to indicate the order of importance of the languages.
212             var q = 10
213
214             // Populate the string builder with the contents of the locales list.
215             for (i in 0 until localeList.size()) {
216                 // Append a comma if there is already an item in the string builder.
217                 if (i > 0) {
218                     localesStringBuilder.append(",")
219                 }
220
221                 // Get the locale from the list.
222                 val locale = localeList[i]
223
224                 // Add the locale to the string.  `locale` by default displays as `en_US`, but WebView uses the `en-US` format.
225                 localesStringBuilder.append(locale.language)
226                 localesStringBuilder.append("-")
227                 localesStringBuilder.append(locale.country)
228
229                 // If not the first locale, append `;q=0.x`, which drops by .1 for each removal from the main locale until q=0.1.
230                 if (q < 10) {
231                     localesStringBuilder.append(";q=0.")
232                     localesStringBuilder.append(q)
233                 }
234
235                 // Decrement `q` if it is greater than 1.
236                 if (q > 1) {
237                     q--
238                 }
239
240                 // Add a second entry for the language only portion of the locale.
241                 localesStringBuilder.append(",")
242                 localesStringBuilder.append(locale.language)
243
244                 // Append `1;q=0.x`, which drops by .1 for each removal form the main locale until q=0.1.
245                 localesStringBuilder.append(";q=0.")
246                 localesStringBuilder.append(q)
247
248                 // Decrement `q` if it is greater than 1.
249                 if (q > 1) {
250                     q--
251                 }
252             }
253
254             // Store the populated string builder in the locale string.
255             localesStringBuilder.toString()
256         } else {  // SDK < 24 only has a primary locale.
257             // Store the locale in the locale string.
258             Locale.getDefault().toString()
259         }
260
261         // Instantiate the proxy helper.
262         val proxyHelper = ProxyHelper()
263
264         // Get the current proxy.
265         val proxy = proxyHelper.getCurrentProxy(this)
266
267         // Make the progress bar visible.
268         progressBar.visibility = View.VISIBLE
269
270         // Set the progress bar to be indeterminate.
271         progressBar.isIndeterminate = true
272
273         // Update the layout.
274         updateLayout(currentUrl)
275
276         // Instantiate the WebView source factory.
277         val webViewSourceFactory: ViewModelProvider.Factory = WebViewSourceFactory(currentUrl, userAgent, localeString, proxy, contentResolver, MainWebViewActivity.executorService)
278
279         // Instantiate the WebView source view model class.
280         webViewSource = ViewModelProvider(this, webViewSourceFactory).get(WebViewSource::class.java)
281
282         // Create a source observer.
283         webViewSource.observeSource().observe(this, { sourceStringArray: Array<SpannableStringBuilder> ->
284             // Populate the text views.  This can take a long time, and freezes the user interface, if the response body is particularly large.
285             requestHeadersTextView.text = sourceStringArray[0]
286             responseMessageTextView.text = sourceStringArray[1]
287             responseHeadersTextView.text = sourceStringArray[2]
288             responseBodyTextView.text = sourceStringArray[3]
289
290             // Hide the progress bar.
291             progressBar.isIndeterminate = false
292             progressBar.visibility = View.GONE
293
294             //Stop the swipe to refresh indicator if it is running
295             swipeRefreshLayout.isRefreshing = false
296         })
297
298         // Create an error observer.
299         webViewSource.observeErrors().observe(this, { errorString: String ->
300             // Display an error snackbar if the string is not `""`.
301             if (errorString != "") {
302                 if (errorString.startsWith("javax.net.ssl.SSLHandshakeException")) {
303                     // Instantiate the untrusted SSL certificate dialog.
304                     val untrustedSslCertificateDialog = UntrustedSslCertificateDialog()
305
306                     // Show the untrusted SSL certificate dialog.
307                     untrustedSslCertificateDialog.show(supportFragmentManager, getString(R.string.invalid_certificate))
308                 } else {
309                     // Display a snackbar with the error message.
310                     Snackbar.make(swipeRefreshLayout, errorString, Snackbar.LENGTH_LONG).show()
311                 }
312             }
313         })
314
315         // Implement swipe to refresh.
316         swipeRefreshLayout.setOnRefreshListener {
317             // Make the progress bar visible.
318             progressBar.visibility = View.VISIBLE
319
320             // Set the progress bar to be indeterminate.
321             progressBar.isIndeterminate = true
322
323             // Get the URL.
324             val urlString = urlEditText.text.toString()
325
326             // Update the layout.
327             updateLayout(urlString)
328
329             // Get the updated source.
330             webViewSource.updateSource(urlString, false)
331         }
332
333         // Set the go button on the keyboard to request new source data.
334         urlEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
335             // Request new source data if the enter key was pressed.
336             if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
337                 // Hide the soft keyboard.
338                 inputMethodManager.hideSoftInputFromWindow(urlEditText.windowToken, 0)
339
340                 // Remove the focus from the URL box.
341                 urlEditText.clearFocus()
342
343                 // Make the progress bar visible.
344                 progressBar.visibility = View.VISIBLE
345
346                 // Set the progress bar to be indeterminate.
347                 progressBar.isIndeterminate = true
348
349                 // Get the URL.
350                 val urlString = urlEditText.text.toString()
351
352                 // Update the layout.
353                 updateLayout(urlString)
354
355                 // Get the updated source.
356                 webViewSource.updateSource(urlString, false)
357
358                 // Consume the key press.
359                 return@setOnKeyListener true
360             } else {
361                 // Do not consume the key press.
362                 return@setOnKeyListener false
363             }
364         }
365     }
366
367     override fun onCreateOptionsMenu(menu: Menu): Boolean {
368         // Inflate the menu.
369         menuInflater.inflate(R.menu.view_source_options_menu, menu)
370
371         // Display the menu.
372         return true
373     }
374
375     override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
376         // Instantiate the about dialog fragment.
377         val aboutDialogFragment: DialogFragment = AboutViewSourceDialog()
378
379         // Show the about alert dialog.
380         aboutDialogFragment.show(supportFragmentManager, getString(R.string.about))
381
382         // Consume the event.
383         return true
384     }
385
386     // This method must be named `goBack()` and must have a View argument to match the default back arrow in the app bar.
387     fun goBack(@Suppress("UNUSED_PARAMETER") view: View) {
388         // Go home.
389         NavUtils.navigateUpFromSameTask(this)
390     }
391
392     override fun loadAnyway() {
393         // Load the URL anyway.
394         webViewSource.updateSource(urlEditText.text.toString(), true)
395     }
396
397     private fun highlightUrlText() {
398         // Get a handle for the URL edit text.
399         val urlEditText = findViewById<EditText>(R.id.url_edittext)
400
401         // Get the URL string.
402         val urlString = urlEditText.text.toString()
403
404         // Highlight the URL according to the protocol.
405         if (urlString.startsWith("file://")) {  // This is a file URL.
406             // De-emphasize only the protocol.
407             urlEditText.text.setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
408         } else if (urlString.startsWith("content://")) {
409             // De-emphasize only the protocol.
410             urlEditText.text.setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
411         } else {  // This is a web URL.
412             // Get the index of the `/` immediately after the domain name.
413             val endOfDomainName = urlString.indexOf("/", urlString.indexOf("//") + 2)
414
415             // Get the base URL.
416             val baseUrl = if (endOfDomainName > 0) {  // There is at least one character after the base URL.
417                 // Get the base URL.
418                 urlString.substring(0, endOfDomainName)
419             } else {  // There are no characters after the base URL.
420                 // Set the base URL to be the entire URL string.
421                 urlString
422             }
423
424             // Get the index of the last `.` in the domain.
425             val lastDotIndex = baseUrl.lastIndexOf(".")
426
427             // Get the index of the penultimate `.` in the domain.
428             val penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1)
429
430             // Markup the beginning of the URL.
431             if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
432                 urlEditText.text.setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
433
434                 // De-emphasize subdomains.
435                 if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
436                     urlEditText.text.setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
437                 }
438             } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
439                 if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
440                     // De-emphasize the protocol and the additional subdomains.
441                     urlEditText.text.setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
442                 } else {  // There is only one subdomain in the domain name.
443                     // De-emphasize only the protocol.
444                     urlEditText.text.setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
445                 }
446             }
447
448             // De-emphasize the text after the domain name.
449             if (endOfDomainName > 0) {
450                 urlEditText.text.setSpan(finalGrayColorSpan, endOfDomainName, urlString.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
451             }
452         }
453     }
454
455     private fun updateLayout(urlString: String) {
456         if (urlString.startsWith("content://")) {  // This is a content URL.
457             // Hide the unused text views.
458             requestHeadersTitleTextView.visibility = View.GONE
459             requestHeadersTextView.visibility = View.GONE
460             responseMessageTitleTextView.visibility = View.GONE
461             responseMessageTextView.visibility = View.GONE
462
463             // Change the text of the remaining title text views.
464             responseHeadersTitleTextView.setText(R.string.content_metadata)
465             responseBodyTitleTextView.setText(R.string.content_data)
466         } else {  // This is not a content URL.
467             // Show the views.
468             requestHeadersTitleTextView.visibility = View.VISIBLE
469             requestHeadersTextView.visibility = View.VISIBLE
470             responseMessageTitleTextView.visibility = View.VISIBLE
471             responseMessageTextView.visibility = View.VISIBLE
472
473             // Restore the text of the other title text views.
474             responseHeadersTitleTextView.setText(R.string.response_headers)
475             responseBodyTitleTextView.setText(R.string.response_body)
476         }
477     }
478 }