]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/AboutActivity.java
Convert a number of files to Kotlin. https://redmine.stoutner.com/issues/641
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / AboutActivity.java
1 /*
2  * Copyright © 2016-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.Manifest;
23 import android.app.Activity;
24 import android.app.Dialog;
25 import android.content.ContentResolver;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.pm.PackageManager;
29 import android.media.MediaScannerConnection;
30 import android.net.Uri;
31 import android.os.Build;
32 import android.os.Bundle;
33 import android.preference.PreferenceManager;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.widget.EditText;
37 import android.widget.LinearLayout;
38 import android.widget.TextView;
39
40 import androidx.annotation.NonNull;
41 import androidx.appcompat.app.ActionBar;
42 import androidx.appcompat.app.AppCompatActivity;
43 import androidx.appcompat.widget.Toolbar;
44 import androidx.core.app.ActivityCompat;
45 import androidx.core.content.ContextCompat;
46 import androidx.core.content.FileProvider;
47 import androidx.fragment.app.DialogFragment;
48 import androidx.viewpager.widget.ViewPager;
49
50 import com.google.android.material.snackbar.Snackbar;
51 import com.google.android.material.tabs.TabLayout;
52
53 import com.stoutner.privacybrowser.adapters.AboutPagerAdapter;
54 import com.stoutner.privacybrowser.R;
55 import com.stoutner.privacybrowser.asynctasks.SaveAboutVersionImage;
56 import com.stoutner.privacybrowser.dialogs.SaveDialog;
57 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
58 import com.stoutner.privacybrowser.fragments.AboutVersionFragment;
59 import com.stoutner.privacybrowser.helpers.FileNameHelper;
60
61 import java.io.BufferedReader;
62 import java.io.BufferedWriter;
63 import java.io.ByteArrayInputStream;
64 import java.io.File;
65 import java.io.FileOutputStream;
66 import java.io.InputStream;
67 import java.io.InputStreamReader;
68 import java.io.OutputStreamWriter;
69 import java.nio.charset.StandardCharsets;
70
71 public class AboutActivity extends AppCompatActivity implements SaveDialog.SaveListener, StoragePermissionDialog.StoragePermissionDialogListener {
72     // Declare the class variables.
73     private String filePathString;
74     private AboutPagerAdapter aboutPagerAdapter;
75
76     // Declare the class views.
77     private LinearLayout aboutVersionLinearLayout;
78
79     @Override
80     protected void onCreate(Bundle savedInstanceState) {
81         // Get a handle for the shared preferences.
82         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
83
84         // Get the screenshot preference.
85         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
86
87         // Disable screenshots if not allowed.
88         if (!allowScreenshots) {
89             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
90         }
91
92         // Set the theme.
93         setTheme(R.style.PrivacyBrowser);
94
95         // Run the default commands.
96         super.onCreate(savedInstanceState);
97
98         // Get the intent that launched the activity.
99         Intent launchingIntent = getIntent();
100
101         // Store the blocklist versions.
102         String[] blocklistVersions = launchingIntent.getStringArrayExtra("blocklist_versions");
103
104         // Remove the incorrect lint warning below that the blocklist versions might be null.
105         assert blocklistVersions != null;
106
107         // Set the content view.
108         setContentView(R.layout.about_coordinatorlayout);
109
110         // Get handles for the views.
111         Toolbar toolbar = findViewById(R.id.about_toolbar);
112         TabLayout aboutTabLayout = findViewById(R.id.about_tablayout);
113         ViewPager aboutViewPager = findViewById(R.id.about_viewpager);
114
115         // Set the action bar.  `SupportActionBar` must be used until the minimum API is >= 21.
116         setSupportActionBar(toolbar);
117
118         // Get a handle for the action bar.
119         final ActionBar actionBar = getSupportActionBar();
120
121         // Remove the incorrect lint warning that the action bar might be null.
122         assert actionBar != null;  //
123
124         // Display the home arrow on action bar.
125         actionBar.setDisplayHomeAsUpEnabled(true);
126
127         // Initialize the about pager adapter.
128         aboutPagerAdapter = new AboutPagerAdapter(getSupportFragmentManager(), getApplicationContext(), blocklistVersions);
129
130         // Setup the ViewPager.
131         aboutViewPager.setAdapter(aboutPagerAdapter);
132
133         // Keep all the tabs in memory.  This prevents the memory usage updater from running multiple times.
134         aboutViewPager.setOffscreenPageLimit(10);
135
136         // Connect the tab layout to the view pager.
137         aboutTabLayout.setupWithViewPager(aboutViewPager);
138     }
139
140     @Override
141     public void onSave(int saveType, DialogFragment dialogFragment) {
142         // Get a handle for the dialog.
143         Dialog dialog = dialogFragment.getDialog();
144
145         // Remove the lint warning below that the dialog might be null.
146         assert dialog != null;
147
148         // Get a handle for the file name edit text.
149         EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
150
151         // Get the file path string.
152         filePathString = fileNameEditText.getText().toString();
153
154         // Get a handle for the about version linear layout.
155         aboutVersionLinearLayout = findViewById(R.id.about_version_linearlayout);
156
157         // check to see if the storage permission is needed.
158         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
159             // Save the file according to the type.
160             switch (saveType) {
161                 case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
162                     // Save the about version text.
163                     saveAsText(filePathString);
164                     break;
165
166                 case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
167                     // Save the about version image.
168                     new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
169                     break;
170             }
171
172             // Reset the file path string.
173             filePathString = "";
174         } else {  // The storage permission has not been granted.
175             // Get the external private directory file.
176             File externalPrivateDirectoryFile = getExternalFilesDir(null);
177
178             // Remove the incorrect lint error below that the file might be null.
179             assert externalPrivateDirectoryFile != null;
180
181             // Get the external private directory string.
182             String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
183
184             // Check to see if the file path is in the external private directory.
185             if (filePathString.startsWith(externalPrivateDirectory)) {  // The file path is in the external private directory.
186                 // Save the webpage according to the type.
187                 switch (saveType) {
188                     case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
189                         // Save the about version text.
190                         saveAsText(filePathString);
191                         break;
192
193                     case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
194                         // Save the about version image.
195                         new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
196                         break;
197                 }
198
199                 // Reset the file path string.
200                 filePathString = "";
201             } else {  // The file path is in a public directory.
202                 // Check if the user has previously denied the storage permission.
203                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
204                     // Declare a storage permission dialog fragment.
205                     DialogFragment storagePermissionDialogFragment;
206
207                     // Instantiate the storage permission alert dialog according to the type.
208                     if (saveType == SaveDialog.SAVE_ABOUT_VERSION_TEXT) {
209                         storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.SAVE_TEXT);
210                     } else {
211                         storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.SAVE_IMAGE);
212                     }
213
214                     // Show the storage permission alert dialog.  The permission will be requested when the dialog is closed.
215                     storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
216                 } else {  // Show the permission request directly.
217                     switch (saveType) {
218                         case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
219                             // Request the write external storage permission.  The text will be saved when it finishes.
220                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, StoragePermissionDialog.SAVE_TEXT);
221                             break;
222
223                         case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
224                             // Request the write external storage permission.  The image will be saved when it finishes.
225                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, StoragePermissionDialog.SAVE_IMAGE);
226                             break;
227                     }
228
229                 }
230             }
231         }
232     }
233
234     @Override
235     public void onCloseStoragePermissionDialog(int requestType) {
236         // Request the write external storage permission according to the request type.  About version will be saved when it finishes.
237         ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestType);
238     }
239
240     @Override
241     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
242         //Only process the results if they exist (this method is triggered when a dialog is presented the first time for an app, but no grant results are included).
243         if (grantResults.length > 0) {
244             // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
245             if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {  // The storage permission was granted.
246                 switch (requestCode) {
247                     case StoragePermissionDialog.SAVE_TEXT:
248                         // Save the about version text.
249                         saveAsText(filePathString);
250                         break;
251
252                     case StoragePermissionDialog.SAVE_IMAGE:
253                         // Save the about version image.
254                         new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
255                         break;
256                 }
257             } else{  // the storage permission was not granted.
258                 // Display an error snackbar.
259                 Snackbar.make(aboutVersionLinearLayout, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
260             }
261
262             // Reset the file path string.
263             filePathString = "";
264         }
265     }
266
267     // The activity result is called after browsing for a file in the save alert dialog.
268     @Override
269     public void onActivityResult(int requestCode, int resultCode, Intent data) {
270         // Run the default commands.
271         super.onActivityResult(requestCode, resultCode, data);
272
273         // Only do something if the user didn't press back from the file picker.
274         if (resultCode == Activity.RESULT_OK) {
275             // Get a handle for the save dialog fragment.
276             DialogFragment saveDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
277
278             // Only update the file name if the dialog still exists.
279             if (saveDialogFragment != null) {
280                 // Get a handle for the save dialog.
281                 Dialog saveDialog = saveDialogFragment.getDialog();
282
283                 // Remove the lint warning below that the dialog might be null.
284                 assert saveDialog != null;
285
286                 // Get a handle for the dialog view.
287                 EditText fileNameEditText = saveDialog.findViewById(R.id.file_name_edittext);
288                 TextView fileExistsWarningTextView = saveDialog.findViewById(R.id.file_exists_warning_textview);
289
290                 // Get the file name URI from the intent.
291                 Uri fileNameUri = data.getData();
292
293                 // Process the file name URI if it is not null.
294                 if (fileNameUri != null) {
295                     // Instantiate a file name helper.
296                     FileNameHelper fileNameHelper = new FileNameHelper();
297
298                     // Convert the file name URI to a file name path.
299                     String fileNamePath = fileNameHelper.convertUriToFileNamePath(fileNameUri);
300
301                     // Set the file name path as the text of the file nam edit text.
302                     fileNameEditText.setText(fileNamePath);
303
304                     // Move the cursor to the end of the file name edit text.
305                     fileNameEditText.setSelection(fileNamePath.length());
306
307                     // Hid ethe file exists warning.
308                     fileExistsWarningTextView.setVisibility(View.GONE);
309                 }
310             }
311         }
312     }
313
314     private void saveAsText(String fileNameString) {
315         try {
316             // Get a handle for the about about version fragment.
317             AboutVersionFragment aboutVersionFragment = (AboutVersionFragment) aboutPagerAdapter.getTabFragment(0);
318
319             // Get the about version text.
320             String aboutVersionString = aboutVersionFragment.getAboutVersionString();
321
322             // Create an input stream with the contents of about version.
323             InputStream aboutVersionInputStream = new ByteArrayInputStream(aboutVersionString.getBytes(StandardCharsets.UTF_8));
324
325             // Create an about version buffered reader.
326             BufferedReader aboutVersionBufferedReader = new BufferedReader(new InputStreamReader(aboutVersionInputStream));
327
328             // Create a file from the file name string.
329             File saveFile = new File(fileNameString);
330
331             // Delete the file if it already exists.
332             if (saveFile.exists()) {
333                 //noinspection ResultOfMethodCallIgnored
334                 saveFile.delete();
335             }
336
337             // Create a file buffered writer.
338             BufferedWriter fileBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
339
340             // Create a transfer string.
341             String transferString;
342
343             // Use the transfer string to copy the about version text from the buffered reader to the buffered writer.
344             while ((transferString = aboutVersionBufferedReader.readLine()) != null) {
345                 // Append the line to the buffered writer.
346                 fileBufferedWriter.append(transferString);
347
348                 // Append a line break.
349                 fileBufferedWriter.append("\n");
350             }
351
352             // Close the buffered reader and writer.
353             aboutVersionBufferedReader.close();
354             fileBufferedWriter.close();
355
356             // Add the file to the list of recent files.  This doesn't currently work, but maybe it will someday.
357             MediaScannerConnection.scanFile(this, new String[] {fileNameString}, new String[] {"text/plain"}, null);
358
359             // Create an about version saved snackbar.
360             Snackbar aboutVersionSavedSnackbar = Snackbar.make(aboutVersionLinearLayout, getString(R.string.file_saved) + "  " + fileNameString, Snackbar.LENGTH_SHORT);
361
362             // Add an open option to the snackbar.
363             aboutVersionSavedSnackbar.setAction(R.string.open, (View view) -> {
364                 // Get a file for the file name string.
365                 File file = new File(fileNameString);
366
367                 // Declare a file URI variable.
368                 Uri fileUri;
369
370                 // Get the URI for the file according to the Android version.
371                 if (Build.VERSION.SDK_INT >= 24) {  // Use a file provider.
372                     fileUri = FileProvider.getUriForFile(this, getString(R.string.file_provider), file);
373                 } else {  // Get the raw file path URI.
374                     fileUri = Uri.fromFile(file);
375                 }
376
377                 // Get a handle for the content resolver.
378                 ContentResolver contentResolver = getContentResolver();
379
380                 // Create an open intent with `ACTION_VIEW`.
381                 Intent openIntent = new Intent(Intent.ACTION_VIEW);
382
383                 // Set the URI and the MIME type.
384                 openIntent.setDataAndType(fileUri, contentResolver.getType(fileUri));
385
386                 // Allow the app to read the file URI.
387                 openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
388
389                 // Show the chooser.
390                 startActivity(Intent.createChooser(openIntent, getString(R.string.open)));
391             });
392
393             // Show the about version saved snackbar.
394             aboutVersionSavedSnackbar.show();
395         } catch (Exception exception) {
396             // Display a snackbar with the error message.
397             Snackbar.make(aboutVersionLinearLayout, getString(R.string.error_saving_file) + "  " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
398         }
399     }
400 }