]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - privacybrowser/activities/ImportExportActivity.java
Add an option to delete all domain settings at once. https://redmine.stoutner.com...
[PrivacyBrowserAndroid.git] / privacybrowser / activities / ImportExportActivity.java
1 /*
2  * Copyright © 2018 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.DialogFragment;
25 import android.content.Intent;
26 import android.content.pm.PackageManager;
27 import android.net.Uri;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.os.Environment;
31 import android.provider.DocumentsContract;
32 import android.support.annotation.NonNull;
33 import android.support.design.widget.Snackbar;
34 import android.support.v4.app.ActivityCompat;
35 import android.support.v4.content.ContextCompat;
36 import android.support.v7.app.ActionBar;
37 import android.support.v7.app.AppCompatActivity;
38 import android.support.v7.widget.Toolbar;
39 import android.text.Editable;
40 import android.text.TextWatcher;
41 import android.view.View;
42 import android.view.WindowManager;
43 import android.widget.Button;
44 import android.widget.EditText;
45 import android.widget.TextView;
46
47 import com.stoutner.privacybrowser.R;
48 import com.stoutner.privacybrowser.dialogs.ImportExportStoragePermissionDialog;
49 import com.stoutner.privacybrowser.helpers.ImportExportDatabaseHelper;
50
51 import java.io.File;
52
53 public class ImportExportActivity extends AppCompatActivity implements ImportExportStoragePermissionDialog.ImportExportStoragePermissionDialogListener {
54     private final static int EXPORT_FILE_PICKER_REQUEST_CODE = 1;
55     private final static int IMPORT_FILE_PICKER_REQUEST_CODE = 2;
56     private final static int EXPORT_REQUEST_CODE = 3;
57     private final static int IMPORT_REQUEST_CODE = 4;
58
59     @Override
60     public void onCreate(Bundle savedInstanceState) {
61         // Disable screenshots if not allowed.
62         if (!MainWebViewActivity.allowScreenshots) {
63             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
64         }
65
66         // Set the activity theme.
67         if (MainWebViewActivity.darkTheme) {
68             setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
69         } else {
70             setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
71         }
72
73         // Run the default commands.
74         super.onCreate(savedInstanceState);
75
76         // Set the content view.
77         setContentView(R.layout.import_export_coordinatorlayout);
78
79         // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
80         Toolbar importExportAppBar = findViewById(R.id.import_export_toolbar);
81         setSupportActionBar(importExportAppBar);
82
83         // Display the home arrow on the support action bar.
84         ActionBar appBar = getSupportActionBar();
85         assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
86         appBar.setDisplayHomeAsUpEnabled(true);
87
88         // Get handles for the views that need to be modified.
89         EditText exportFileEditText = findViewById(R.id.export_file_edittext);
90         Button exportButton = findViewById(R.id.export_button);
91         EditText importFileEditText = findViewById(R.id.import_file_edittext);
92         Button importButton = findViewById(R.id.import_button);
93         TextView storagePermissionTextView = findViewById(R.id.import_export_storage_permission_textview);
94
95         // Initially disable the buttons.
96         exportButton.setEnabled(false);
97         importButton.setEnabled(false);
98
99         // Enable the export button when the export file EditText isn't empty.
100         exportFileEditText.addTextChangedListener(new TextWatcher() {
101             @Override
102             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
103                 // Do nothing.
104             }
105
106             @Override
107             public void onTextChanged(CharSequence s, int start, int before, int count) {
108                 // Do nothing.
109             }
110
111             @Override
112             public void afterTextChanged(Editable s) {
113                 exportButton.setEnabled(!exportFileEditText.getText().toString().isEmpty());
114             }
115         });
116
117         // Enable the import button when the export file EditText isn't empty.
118         importFileEditText.addTextChangedListener(new TextWatcher() {
119             @Override
120             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
121                 // Do nothing.
122             }
123
124             @Override
125             public void onTextChanged(CharSequence s, int start, int before, int count) {
126                 // Do nothing.
127             }
128
129             @Override
130             public void afterTextChanged(Editable s) {
131                 importButton.setEnabled(!importFileEditText.getText().toString().isEmpty());
132             }
133         });
134
135         // Set the initial file paths.
136         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
137             // Create a string for the external public path.
138             String EXTERNAL_PUBLIC_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + getString(R.string.privacy_browser_settings);
139
140             // Set the default path.
141             exportFileEditText.setText(EXTERNAL_PUBLIC_PATH);
142             importFileEditText.setText(EXTERNAL_PUBLIC_PATH);
143         } else {  // The storage permission has not been granted.
144             // Create a string for the external private path.
145             String EXTERNAL_PRIVATE_PATH = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/" + getString(R.string.privacy_browser_settings);
146
147             // Set the default path.
148             exportFileEditText.setText(EXTERNAL_PRIVATE_PATH);
149             importFileEditText.setText(EXTERNAL_PRIVATE_PATH);
150         }
151
152         // Hide the storage permissions TextView on API < 23 as permissions on older devices are automatically granted.
153         if (Build.VERSION.SDK_INT < 23) {
154             storagePermissionTextView.setVisibility(View.GONE);
155         }
156     }
157
158     public void exportBrowse(View view) {
159         // Create the file picker intent.
160         Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
161
162         // Set the intent MIME type to include all files.
163         intent.setType("*/*");
164
165         // Set the initial export file name.
166         intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.privacy_browser_settings));
167
168         // Set the initial directory if API >= 26.
169         if (Build.VERSION.SDK_INT >= 26) {
170             intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
171         }
172
173         // Specify that a file that can be opened is requested.
174         intent.addCategory(Intent.CATEGORY_OPENABLE);
175
176         // Launch the file picker.
177         startActivityForResult(intent, EXPORT_FILE_PICKER_REQUEST_CODE);
178     }
179
180     public void onClickExport(View view) {
181         // Check to see if the storage permission has been granted.
182         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // Storage permission granted.
183             // Export the settings.
184             exportSettings();
185         } else {  // Storage permission not granted.
186             // Get a handle for the export file EditText.
187             EditText exportFileEditText = findViewById(R.id.export_file_edittext);
188
189             // Get the export file string.
190             String exportFileString = exportFileEditText.getText().toString();
191
192             // Get the external private directory `File`.
193             File externalPrivateDirectoryFile = getApplicationContext().getExternalFilesDir(null);
194
195             // Remove the lint error below that the `File` might be null.
196             assert externalPrivateDirectoryFile != null;
197
198             // Get the external private directory string.
199             String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
200
201             // Check to see if the export file path is in the external private directory.
202             if (exportFileString.startsWith(externalPrivateDirectory)) {  // The export path is in the external private directory.
203                 // Export the settings.
204                 exportSettings();
205             } else {  // The export path is in a public directory.
206                 // Check if the user has previously denied the storage permission.
207                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
208                     // Instantiate the storage permission alert dialog and set the type to EXPORT_SETTINGS.
209                     DialogFragment importExportStoragePermissionDialogFragment = ImportExportStoragePermissionDialog.type(ImportExportStoragePermissionDialog.EXPORT_SETTINGS);
210
211                     // Show the storage permission alert dialog.  The permission will be requested when the dialog is closed.
212                     importExportStoragePermissionDialogFragment.show(getFragmentManager(), getString(R.string.storage_permission));
213                 } else {  // Show the permission request directly.
214                     // Request the storage permission.  The export will be run when it finishes.
215                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXPORT_REQUEST_CODE);
216                 }
217             }
218         }
219     }
220
221     public void importBrowse(View view) {
222         // Create the file picker intent.
223         Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
224
225         // Set the intent MIME type to include all files.
226         intent.setType("*/*");
227
228         // Set the initial directory if API >= 26.
229         if (Build.VERSION.SDK_INT >= 26) {
230             intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
231         }
232
233         // Specify that a file that can be opened is requested.
234         intent.addCategory(Intent.CATEGORY_OPENABLE);
235
236         // Launch the file picker.
237         startActivityForResult(intent, IMPORT_FILE_PICKER_REQUEST_CODE);
238     }
239
240     public void onClickImport(View view) {
241         // Check to see if the storage permission has been granted.
242         if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // Storage permission granted.
243             // Import the settings.
244             importSettings();
245         } else {  // Storage permission not granted.
246             // Get a handle for the import file EditText.
247             EditText importFileEditText = findViewById(R.id.import_file_edittext);
248
249             // Get the import file string.
250             String importFileString = importFileEditText.getText().toString();
251
252             // Get the external private directory `File`.
253             File externalPrivateDirectoryFile = getApplicationContext().getExternalFilesDir(null);
254
255             // Remove the lint error below that `File` might be null.
256             assert externalPrivateDirectoryFile != null;
257
258             // Get the external private directory string.
259             String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
260
261             // Check to see if the import file path is in the external private directory.
262             if (importFileString.startsWith(externalPrivateDirectory)) {  // The import path is in the external private directory.
263                 // Import the settings.
264                 importSettings();
265             } else {  // The import path is in a public directory.
266                 // Check if the user has previously denied the storage permission.
267                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
268                     // Instantiate the storage permission alert dialog and set the type to IMPORT_SETTINGS.
269                     DialogFragment importExportStoragePermissionDialogFragment = ImportExportStoragePermissionDialog.type(ImportExportStoragePermissionDialog.IMPORT_SETTINGS);
270
271                     // Show the storage permission alert dialog.  The permission will be requested when the dialog is closed.
272                     importExportStoragePermissionDialogFragment.show(getFragmentManager(), getString(R.string.storage_permission));
273                 } else {  // Show the permission request directly.
274                     // Request the storage permission.  The export will be run when it finishes.
275                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, IMPORT_REQUEST_CODE);
276                 }
277             }
278         }
279     }
280
281     @Override
282     public void onActivityResult(int requestCode, int resultCode, Intent data) {
283         // Don't do anything if the user pressed back from the file picker.
284         if (resultCode == Activity.RESULT_OK) {
285             // Run the commands for the specific request code.
286             switch (requestCode) {
287                 case EXPORT_FILE_PICKER_REQUEST_CODE:
288                     // Get a handle for the export file EditText.
289                     EditText exportFileEditText = findViewById(R.id.export_file_edittext);
290
291                     // Get the selected export file.
292                     Uri exportUri = data.getData();
293
294                     // Remove the lint warning that the export URI might be null.
295                     assert exportUri != null;
296
297                     // Get the raw export path.
298                     String rawExportPath = exportUri.getPath();
299
300                     // Remove the warning that the raw export path might be null.
301                     assert rawExportPath != null;
302
303                     // Check to see if the rawExportPath includes a valid storage location.
304                     if (rawExportPath.contains(":")) {  // The path is valid.
305                         // Split the path into the initial content uri and the path information.
306                         String exportContentPath = rawExportPath.substring(0, rawExportPath.indexOf(":"));
307                         String exportFilePath = rawExportPath.substring(rawExportPath.indexOf(":") + 1);
308
309                         // Create the export path string.
310                         String exportPath;
311
312                         // Construct the export path.
313                         switch (exportContentPath) {
314                             // The documents home has a special content path.
315                             case "/document/home":
316                                 exportPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + exportFilePath;
317                                 break;
318
319                             // Everything else for the primary user should be in `/document/primary`.
320                             case "/document/primary":
321                                 exportPath = Environment.getExternalStorageDirectory() + "/" + exportFilePath;
322                                 break;
323
324                             // Just in case, catch everything else and place it in the external storage directory.
325                             default:
326                                 exportPath = Environment.getExternalStorageDirectory() + "/" + exportFilePath;
327                                 break;
328                         }
329
330                         // Set the export file URI as the text for the export file EditText.
331                         exportFileEditText.setText(exportPath);
332                     } else {  // The path is invalid.
333                         Snackbar.make(exportFileEditText, rawExportPath + " + " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
334                     }
335                     break;
336
337                 case IMPORT_FILE_PICKER_REQUEST_CODE:
338                     // Get a handle for the import file EditText.
339                     EditText importFileEditText = findViewById(R.id.import_file_edittext);
340
341                     // Get the selected import file.
342                     Uri importUri = data.getData();
343
344                     // Remove the lint warning that the import URI might be null.
345                     assert importUri != null;
346
347                     // Get the raw import path.
348                     String rawImportPath = importUri.getPath();
349
350                     // Remove the warning that the raw import path might be null.
351                     assert rawImportPath != null;
352
353                     // Check to see if the rawExportPath includes a valid storage location.
354                     if (rawImportPath.contains(":")) {  // The path is valid.
355                         // Split the path into the initial content uri and the path information.
356                         String importContentPath = rawImportPath.substring(0, rawImportPath.indexOf(":"));
357                         String importFilePath = rawImportPath.substring(rawImportPath.indexOf(":") + 1);
358
359                         // Create the export path string.
360                         String importPath;
361
362                         // Construct the export path.
363                         switch (importContentPath) {
364                             // The documents folder has a special content path.
365                             case "/document/home":
366                                 importPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + importFilePath;
367                                 break;
368
369                             // Everything else for the primary user should be in `/document/primary`.
370                             case "/document/primary":
371                                 importPath = Environment.getExternalStorageDirectory() + "/" + importFilePath;
372                                 break;
373
374                             // Just in case, catch everything else and place it in the external storage directory.
375                             default:
376                                 importPath = Environment.getExternalStorageDirectory() + "/" + importFilePath;
377                                 break;
378                         }
379
380                         // Set the export file URI as the text for the export file EditText.
381                         importFileEditText.setText(importPath);
382                     } else {  // The path is invalid.
383                         Snackbar.make(importFileEditText, rawImportPath + " + " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
384                     }
385                     break;
386             }
387         }
388     }
389
390     @Override
391     public void onCloseImportExportStoragePermissionDialog(int type) {
392         // Request the storage permission based on the button that was pressed.
393         switch (type) {
394             case ImportExportStoragePermissionDialog.EXPORT_SETTINGS:
395                 // Request the storage permission.  The export will be run when it finishes.
396                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXPORT_REQUEST_CODE);
397                 break;
398
399             case ImportExportStoragePermissionDialog.IMPORT_SETTINGS:
400                 // Request the storage permission.  The import will be run when it finishes.
401                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, IMPORT_REQUEST_CODE);
402                 break;
403         }
404     }
405
406     @Override
407     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
408         switch (requestCode) {
409             case EXPORT_REQUEST_CODE:
410                 // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
411                 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {  // The storage permission was granted.
412                     // Export the settings.
413                     exportSettings();
414                 } else {  // The storage permission was not granted.
415                     // Get a handle for the export file EditText.
416                     EditText exportFileEditText = findViewById(R.id.export_file_edittext);
417
418                     // Display an error snackbar.
419                     Snackbar.make(exportFileEditText, getString(R.string.cannot_export), Snackbar.LENGTH_LONG).show();
420                 }
421                 break;
422
423             case IMPORT_REQUEST_CODE:
424                 // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
425                 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {  // The storage permission was granted.
426                     // Import the settings.
427                     importSettings();
428                 } else {  // The storage permission was not granted.
429                     // Get a handle for the import file EditText.
430                     EditText importFileEditText = findViewById(R.id.import_file_edittext);
431
432                     // Display an error snackbar.
433                     Snackbar.make(importFileEditText, getString(R.string.cannot_import), Snackbar.LENGTH_LONG).show();
434                 }
435                 break;
436         }
437     }
438
439     private void exportSettings() {
440         // Get a handle for the export file EditText.
441         EditText exportFileEditText = findViewById(R.id.export_file_edittext);
442
443         // Get the export file string.
444         String exportFileString = exportFileEditText.getText().toString();
445
446         // Set the export file.
447         File exportFile = new File(exportFileString);
448
449         // Instantiate the import export database helper.
450         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
451
452         // Export the unencrypted file.
453         String exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, getApplicationContext());
454
455         // Show a disposition snackbar.
456         if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
457             Snackbar.make(exportFileEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
458         } else {
459             Snackbar.make(exportFileEditText, getString(R.string.export_failed) + "  " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
460         }
461     }
462
463     private void importSettings() {
464         // Get a handle for the import file EditText.
465         EditText importFileEditText = findViewById(R.id.import_file_edittext);
466
467         // Get the import file string.
468         String importFileString = importFileEditText.getText().toString();
469
470         // Set the import file.
471         File importFile = new File(importFileString);
472
473         // Instantiate the import export database helper.
474         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
475
476         // Import the unencrypted file.
477         String importStatus = importExportDatabaseHelper.importUnencrypted(importFile, getApplicationContext());
478
479         // Respond to the import disposition.
480         if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {  // The import was successful.
481             // Create an intent to restart Privacy Browser.
482             Intent restartIntent = getParentActivityIntent();
483
484             // Assert that the intent is not null to remove the lint error below.
485             assert restartIntent != null;
486
487             // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack.  It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
488             restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
489
490             // Make it so.
491             startActivity(restartIntent);
492         } else {  // The import was not successful.
493             // Display a snack bar with the import error.
494             Snackbar.make(importFileEditText, getString(R.string.import_failed) + "  " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
495         }
496     }
497 }