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