2 * Copyright © 2018 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.activities;
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;
47 import com.stoutner.privacybrowser.R;
48 import com.stoutner.privacybrowser.dialogs.ImportExportStoragePermissionDialog;
49 import com.stoutner.privacybrowser.helpers.ImportExportDatabaseHelper;
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;
60 public void onCreate(Bundle savedInstanceState) {
61 // Disable screenshots if not allowed.
62 if (!MainWebViewActivity.allowScreenshots) {
63 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
66 // Set the activity theme.
67 if (MainWebViewActivity.darkTheme) {
68 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
70 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
73 // Run the default commands.
74 super.onCreate(savedInstanceState);
76 // Set the content view.
77 setContentView(R.layout.import_export_coordinatorlayout);
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);
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);
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);
95 // Initially disable the buttons.
96 exportButton.setEnabled(false);
97 importButton.setEnabled(false);
99 // Enable the export button when the export file EditText isn't empty.
100 exportFileEditText.addTextChangedListener(new TextWatcher() {
102 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
107 public void onTextChanged(CharSequence s, int start, int before, int count) {
112 public void afterTextChanged(Editable s) {
113 exportButton.setEnabled(!exportFileEditText.getText().toString().isEmpty());
117 // Enable the import button when the export file EditText isn't empty.
118 importFileEditText.addTextChangedListener(new TextWatcher() {
120 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
125 public void onTextChanged(CharSequence s, int start, int before, int count) {
130 public void afterTextChanged(Editable s) {
131 importButton.setEnabled(!importFileEditText.getText().toString().isEmpty());
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";
140 // Set the default path.
141 exportFileEditText.setText(EXTERNAL_PRIVATE_PATH);
142 importFileEditText.setText(EXTERNAL_PRIVATE_PATH);
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);
151 public void exportBrowse(View view) {
152 // Create the file picker intent.
153 Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
155 // Set the intent MIME type to include all files.
156 intent.setType("*/*");
158 // Set the initial export file name.
159 intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.privacy_browser_backup));
161 // Set the initial directory if API >= 26.
162 if (Build.VERSION.SDK_INT >= 26) {
163 intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
166 // Specify that a file that can be opened is requested.
167 intent.addCategory(Intent.CATEGORY_OPENABLE);
169 // Launch the file picker.
170 startActivityForResult(intent, EXPORT_FILE_PICKER_REQUEST_CODE);
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.
178 } else { // Storage permission not granted.
179 // Get a handle for the export file EditText.
180 EditText exportFileEditText = findViewById(R.id.export_file_edittext);
182 // Get the export file string.
183 String exportFileString = exportFileEditText.getText().toString();
185 // Get the external private directory `File`.
186 File externalPrivateDirectoryFile = getApplicationContext().getExternalFilesDir(null);
188 // Remove the lint error below that the `File` might be null.
189 assert externalPrivateDirectoryFile != null;
191 // Get the external private directory string.
192 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
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.
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);
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);
214 public void importBrowse(View view) {
215 // Create the file picker intent.
216 Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
218 // Set the intent MIME type to include all files.
219 intent.setType("*/*");
221 // Set the initial directory if API >= 26.
222 if (Build.VERSION.SDK_INT >= 26) {
223 intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
226 // Specify that a file that can be opened is requested.
227 intent.addCategory(Intent.CATEGORY_OPENABLE);
229 // Launch the file picker.
230 startActivityForResult(intent, IMPORT_FILE_PICKER_REQUEST_CODE);
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.
238 } else { // Storage permission not granted.
239 // Get a handle for the import file EditText.
240 EditText importFileEditText = findViewById(R.id.import_file_edittext);
242 // Get the import file string.
243 String importFileString = importFileEditText.getText().toString();
245 // Get the external private directory `File`.
246 File externalPrivateDirectoryFile = getApplicationContext().getExternalFilesDir(null);
248 // Remove the lint error below that `File` might be null.
249 assert externalPrivateDirectoryFile != null;
251 // Get the external private directory string.
252 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
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.
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);
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);
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);
284 // Get the selected export file.
285 Uri exportUri = data.getData();
287 // Remove the lint warning that the export URI might be null.
288 assert exportUri != null;
290 // Get the raw export path.
291 String rawExportPath = exportUri.getPath();
293 // Remove the warning that the raw export path might be null.
294 assert rawExportPath != null;
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);
302 // Create the export path string.
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;
312 // Everything else for the primary user should be in `/document/primary`.
313 case "/document/primary":
314 exportPath = Environment.getExternalStorageDirectory() + "/" + exportFilePath;
317 // Just in case, catch everything else and place it in the external storage directory.
319 exportPath = Environment.getExternalStorageDirectory() + "/" + exportFilePath;
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();
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);
334 // Get the selected import file.
335 Uri importUri = data.getData();
337 // Remove the lint warning that the import URI might be null.
338 assert importUri != null;
340 // Get the raw import path.
341 String rawImportPath = importUri.getPath();
343 // Remove the warning that the raw import path might be null.
344 assert rawImportPath != null;
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);
352 // Create the export path string.
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;
362 // Everything else for the primary user should be in `/document/primary`.
363 case "/document/primary":
364 importPath = Environment.getExternalStorageDirectory() + "/" + importFilePath;
367 // Just in case, catch everything else and place it in the external storage directory.
369 importPath = Environment.getExternalStorageDirectory() + "/" + importFilePath;
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();
384 public void onCloseImportExportStoragePermissionDialog(int type) {
385 // Request the storage permission based on the button that was pressed.
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);
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);
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.
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);
411 // Display an error snackbar.
412 Snackbar.make(exportFileEditText, getString(R.string.cannot_export), Snackbar.LENGTH_LONG).show();
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.
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);
425 // Display an error snackbar.
426 Snackbar.make(importFileEditText, getString(R.string.cannot_import), Snackbar.LENGTH_LONG).show();
432 private void exportSettings() {
433 // Get a handle for the export file EditText.
434 EditText exportFileEditText = findViewById(R.id.export_file_edittext);
436 // Get the export file string.
437 String exportFileString = exportFileEditText.getText().toString();
439 // Set the export file.
440 File exportFile = new File(exportFileString);
442 // Instantiate the import export database helper.
443 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
445 // Export the unencrypted file.
446 String exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, getApplicationContext());
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();
452 Snackbar.make(exportFileEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
456 private void importSettings() {
457 // Get a handle for the import file EditText.
458 EditText importFileEditText = findViewById(R.id.import_file_edittext);
460 // Get the import file string.
461 String importFileString = importFileEditText.getText().toString();
463 // Set the import file.
464 File importFile = new File(importFileString);
466 // Instantiate the import export database helper.
467 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
469 // Import the unencrypted file.
470 String importStatus = importExportDatabaseHelper.importUnencrypted(importFile, getApplicationContext());
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();
477 // Assert that the intent is not null to remove the lint error below.
478 assert restartIntent != null;
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);
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();