]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/ImportExportActivity.java
Add import and export of settings. https://redmine.stoutner.com/issues/23
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / 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 default download file path if the storage permission has not been granted.
136         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
137             // Create a string for the external private path.
138             String EXTERNAL_PRIVATE_PATH = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/Privacy Browser Backup";
139
140             // Set the default path.
141             exportFileEditText.setText(EXTERNAL_PRIVATE_PATH);
142             importFileEditText.setText(EXTERNAL_PRIVATE_PATH);
143         }
144
145         // Hide the storage permissions TextView on API < 23 as permissions on older devices are automatically granted.
146         if (Build.VERSION.SDK_INT < 23) {
147             storagePermissionTextView.setVisibility(View.GONE);
148         }
149     }
150
151     public void exportBrowse(View view) {
152         // Create the file picker intent.
153         Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
154
155         // Set the intent MIME type to include all files.
156         intent.setType("*/*");
157
158         // Set the initial export file name.
159         intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.privacy_browser_backup));
160
161         // Set the initial directory if API >= 26.
162         if (Build.VERSION.SDK_INT >= 26) {
163             intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
164         }
165
166         // Specify that a file that can be opened is requested.
167         intent.addCategory(Intent.CATEGORY_OPENABLE);
168
169         // Launch the file picker.
170         startActivityForResult(intent, EXPORT_FILE_PICKER_REQUEST_CODE);
171     }
172
173     public void onClickExport(View view) {
174         // Check to see if the storage permission has been granted.
175         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // Storage permission granted.
176             // Export the settings.
177             exportSettings();
178         } else {  // Storage permission not granted.
179             // Get a handle for the export file EditText.
180             EditText exportFileEditText = findViewById(R.id.export_file_edittext);
181
182             // Get the export file string.
183             String exportFileString = exportFileEditText.getText().toString();
184
185             // Get the external private directory `File`.
186             File externalPrivateDirectoryFile = getApplicationContext().getExternalFilesDir(null);
187
188             // Remove the lint error below that the `File` might be null.
189             assert externalPrivateDirectoryFile != null;
190
191             // Get the external private directory string.
192             String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
193
194             // Check to see if the export file path is in the external private directory.
195             if (exportFileString.startsWith(externalPrivateDirectory)) {  // The export path is in the external private directory.
196                 // Export the settings.
197                 exportSettings();
198             } else {  // The export 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                     // Instantiate the storage permission alert dialog and set the type to EXPORT_SETTINGS.
202                     DialogFragment importExportStoragePermissionDialogFragment = ImportExportStoragePermissionDialog.type(ImportExportStoragePermissionDialog.EXPORT_SETTINGS);
203
204                     // Show the storage permission alert dialog.  The permission will be requested when the dialog is closed.
205                     importExportStoragePermissionDialogFragment.show(getFragmentManager(), getString(R.string.storage_permission));
206                 } else {  // Show the permission request directly.
207                     // Request the storage permission.  The export will be run when it finishes.
208                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXPORT_REQUEST_CODE);
209                 }
210             }
211         }
212     }
213
214     public void importBrowse(View view) {
215         // Create the file picker intent.
216         Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
217
218         // Set the intent MIME type to include all files.
219         intent.setType("*/*");
220
221         // Set the initial directory if API >= 26.
222         if (Build.VERSION.SDK_INT >= 26) {
223             intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
224         }
225
226         // Specify that a file that can be opened is requested.
227         intent.addCategory(Intent.CATEGORY_OPENABLE);
228
229         // Launch the file picker.
230         startActivityForResult(intent, IMPORT_FILE_PICKER_REQUEST_CODE);
231     }
232
233     public void onClickImport(View view) {
234         // Check to see if the storage permission has been granted.
235         if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // Storage permission granted.
236             // Import the settings.
237             importSettings();
238         } else {  // Storage permission not granted.
239             // Get a handle for the import file EditText.
240             EditText importFileEditText = findViewById(R.id.import_file_edittext);
241
242             // Get the import file string.
243             String importFileString = importFileEditText.getText().toString();
244
245             // Get the external private directory `File`.
246             File externalPrivateDirectoryFile = getApplicationContext().getExternalFilesDir(null);
247
248             // Remove the lint error below that `File` might be null.
249             assert externalPrivateDirectoryFile != null;
250
251             // Get the external private directory string.
252             String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
253
254             // Check to see if the import file path is in the external private directory.
255             if (importFileString.startsWith(externalPrivateDirectory)) {  // The import path is in the external private directory.
256                 // Import the settings.
257                 importSettings();
258             } else {  // The import path is in a public directory.
259                 // Check if the user has previously denied the storage permission.
260                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
261                     // Instantiate the storage permission alert dialog and set the type to IMPORT_SETTINGS.
262                     DialogFragment importExportStoragePermissionDialogFragment = ImportExportStoragePermissionDialog.type(ImportExportStoragePermissionDialog.IMPORT_SETTINGS);
263
264                     // Show the storage permission alert dialog.  The permission will be requested when the dialog is closed.
265                     importExportStoragePermissionDialogFragment.show(getFragmentManager(), getString(R.string.storage_permission));
266                 } else {  // Show the permission request directly.
267                     // Request the storage permission.  The export will be run when it finishes.
268                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, IMPORT_REQUEST_CODE);
269                 }
270             }
271         }
272     }
273
274     @Override
275     public void onActivityResult(int requestCode, int resultCode, Intent data) {
276         // Don't do anything if the user pressed back from the file picker.
277         if (resultCode == Activity.RESULT_OK) {
278             // Run the commands for the specific request code.
279             switch (requestCode) {
280                 case EXPORT_FILE_PICKER_REQUEST_CODE:
281                     // Get a handle for the export file EditText.
282                     EditText exportFileEditText = findViewById(R.id.export_file_edittext);
283
284                     // Get the selected export file.
285                     Uri exportUri = data.getData();
286
287                     // Remove the lint warning that the export URI might be null.
288                     assert exportUri != null;
289
290                     // Get the raw export path.
291                     String rawExportPath = exportUri.getPath();
292
293                     // Remove the warning that the raw export path might be null.
294                     assert rawExportPath != null;
295
296                     // Check to see if the rawExportPath includes a valid storage location.
297                     if (rawExportPath.contains(":")) {  // The path is valid.
298                         // Split the path into the initial content uri and the path information.
299                         String exportContentPath = rawExportPath.substring(0, rawExportPath.indexOf(":"));
300                         String exportFilePath = rawExportPath.substring(rawExportPath.indexOf(":") + 1);
301
302                         // Create the export path string.
303                         String exportPath;
304
305                         // Construct the export path.
306                         switch (exportContentPath) {
307                             // The documents home has a special content path.
308                             case "/document/home":
309                                 exportPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + exportFilePath;
310                                 break;
311
312                             // Everything else for the primary user should be in `/document/primary`.
313                             case "/document/primary":
314                                 exportPath = Environment.getExternalStorageDirectory() + "/" + exportFilePath;
315                                 break;
316
317                             // Just in case, catch everything else and place it in the external storage directory.
318                             default:
319                                 exportPath = Environment.getExternalStorageDirectory() + "/" + exportFilePath;
320                                 break;
321                         }
322
323                         // Set the export file URI as the text for the export file EditText.
324                         exportFileEditText.setText(exportPath);
325                     } else {  // The path is invalid.
326                         Snackbar.make(exportFileEditText, rawExportPath + " + " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
327                     }
328                     break;
329
330                 case IMPORT_FILE_PICKER_REQUEST_CODE:
331                     // Get a handle for the import file EditText.
332                     EditText importFileEditText = findViewById(R.id.import_file_edittext);
333
334                     // Get the selected import file.
335                     Uri importUri = data.getData();
336
337                     // Remove the lint warning that the import URI might be null.
338                     assert importUri != null;
339
340                     // Get the raw import path.
341                     String rawImportPath = importUri.getPath();
342
343                     // Remove the warning that the raw import path might be null.
344                     assert rawImportPath != null;
345
346                     // Check to see if the rawExportPath includes a valid storage location.
347                     if (rawImportPath.contains(":")) {  // The path is valid.
348                         // Split the path into the initial content uri and the path information.
349                         String importContentPath = rawImportPath.substring(0, rawImportPath.indexOf(":"));
350                         String importFilePath = rawImportPath.substring(rawImportPath.indexOf(":") + 1);
351
352                         // Create the export path string.
353                         String importPath;
354
355                         // Construct the export path.
356                         switch (importContentPath) {
357                             // The documents folder has a special content path.
358                             case "/document/home":
359                                 importPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + importFilePath;
360                                 break;
361
362                             // Everything else for the primary user should be in `/document/primary`.
363                             case "/document/primary":
364                                 importPath = Environment.getExternalStorageDirectory() + "/" + importFilePath;
365                                 break;
366
367                             // Just in case, catch everything else and place it in the external storage directory.
368                             default:
369                                 importPath = Environment.getExternalStorageDirectory() + "/" + importFilePath;
370                                 break;
371                         }
372
373                         // Set the export file URI as the text for the export file EditText.
374                         importFileEditText.setText(importPath);
375                     } else {  // The path is invalid.
376                         Snackbar.make(importFileEditText, rawImportPath + " + " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
377                     }
378                     break;
379             }
380         }
381     }
382
383     @Override
384     public void onCloseImportExportStoragePermissionDialog(int type) {
385         // Request the storage permission based on the button that was pressed.
386         switch (type) {
387             case ImportExportStoragePermissionDialog.EXPORT_SETTINGS:
388                 // Request the storage permission.  The export will be run when it finishes.
389                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXPORT_REQUEST_CODE);
390                 break;
391
392             case ImportExportStoragePermissionDialog.IMPORT_SETTINGS:
393                 // Request the storage permission.  The import will be run when it finishes.
394                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, IMPORT_REQUEST_CODE);
395                 break;
396         }
397     }
398
399     @Override
400     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
401         switch (requestCode) {
402             case EXPORT_REQUEST_CODE:
403                 // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
404                 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {  // The storage permission was granted.
405                     // Export the settings.
406                     exportSettings();
407                 } else {  // The storage permission was not granted.
408                     // Get a handle for the export file EditText.
409                     EditText exportFileEditText = findViewById(R.id.export_file_edittext);
410
411                     // Display an error snackbar.
412                     Snackbar.make(exportFileEditText, getString(R.string.cannot_export), Snackbar.LENGTH_LONG).show();
413                 }
414                 break;
415
416             case IMPORT_REQUEST_CODE:
417                 // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
418                 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {  // The storage permission was granted.
419                     // Import the settings.
420                     importSettings();
421                 } else {  // The storage permission was not granted.
422                     // Get a handle for the import file EditText.
423                     EditText importFileEditText = findViewById(R.id.import_file_edittext);
424
425                     // Display an error snackbar.
426                     Snackbar.make(importFileEditText, getString(R.string.cannot_import), Snackbar.LENGTH_LONG).show();
427                 }
428                 break;
429         }
430     }
431
432     private void exportSettings() {
433         // Get a handle for the export file EditText.
434         EditText exportFileEditText = findViewById(R.id.export_file_edittext);
435
436         // Get the export file string.
437         String exportFileString = exportFileEditText.getText().toString();
438
439         // Set the export file.
440         File exportFile = new File(exportFileString);
441
442         // Instantiate the import export database helper.
443         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
444
445         // Export the unencrypted file.
446         String exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, getApplicationContext());
447
448         // Show a disposition snackbar.
449         if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
450             Snackbar.make(exportFileEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
451         } else {
452             Snackbar.make(exportFileEditText, getString(R.string.export_failed) + "  " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
453         }
454     }
455
456     private void importSettings() {
457         // Get a handle for the import file EditText.
458         EditText importFileEditText = findViewById(R.id.import_file_edittext);
459
460         // Get the import file string.
461         String importFileString = importFileEditText.getText().toString();
462
463         // Set the import file.
464         File importFile = new File(importFileString);
465
466         // Instantiate the import export database helper.
467         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
468
469         // Import the unencrypted file.
470         String importStatus = importExportDatabaseHelper.importUnencrypted(importFile, getApplicationContext());
471
472         // Respond to the import disposition.
473         if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {  // The import was successful.
474             // Create an intent to restart Privacy Browser.
475             Intent restartIntent = getParentActivityIntent();
476
477             // Assert that the intent is not null to remove the lint error below.
478             assert restartIntent != null;
479
480             // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack.  It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
481             restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
482
483             // Make it so.
484             startActivity(restartIntent);
485         } else {  // The import was not successful.
486             // Display a snack bar with the import error.
487             Snackbar.make(importFileEditText, getString(R.string.import_failed) + "  " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
488         }
489     }
490 }