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 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);
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);
147 // Set the default path.
148 exportFileEditText.setText(EXTERNAL_PRIVATE_PATH);
149 importFileEditText.setText(EXTERNAL_PRIVATE_PATH);
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);
158 public void exportBrowse(View view) {
159 // Create the file picker intent.
160 Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
162 // Set the intent MIME type to include all files.
163 intent.setType("*/*");
165 // Set the initial export file name.
166 intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.privacy_browser_settings));
168 // Set the initial directory if API >= 26.
169 if (Build.VERSION.SDK_INT >= 26) {
170 intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
173 // Specify that a file that can be opened is requested.
174 intent.addCategory(Intent.CATEGORY_OPENABLE);
176 // Launch the file picker.
177 startActivityForResult(intent, EXPORT_FILE_PICKER_REQUEST_CODE);
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.
185 } else { // Storage permission not granted.
186 // Get a handle for the export file EditText.
187 EditText exportFileEditText = findViewById(R.id.export_file_edittext);
189 // Get the export file string.
190 String exportFileString = exportFileEditText.getText().toString();
192 // Get the external private directory `File`.
193 File externalPrivateDirectoryFile = getApplicationContext().getExternalFilesDir(null);
195 // Remove the lint error below that the `File` might be null.
196 assert externalPrivateDirectoryFile != null;
198 // Get the external private directory string.
199 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
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.
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);
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);
221 public void importBrowse(View view) {
222 // Create the file picker intent.
223 Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
225 // Set the intent MIME type to include all files.
226 intent.setType("*/*");
228 // Set the initial directory if API >= 26.
229 if (Build.VERSION.SDK_INT >= 26) {
230 intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
233 // Specify that a file that can be opened is requested.
234 intent.addCategory(Intent.CATEGORY_OPENABLE);
236 // Launch the file picker.
237 startActivityForResult(intent, IMPORT_FILE_PICKER_REQUEST_CODE);
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.
245 } else { // Storage permission not granted.
246 // Get a handle for the import file EditText.
247 EditText importFileEditText = findViewById(R.id.import_file_edittext);
249 // Get the import file string.
250 String importFileString = importFileEditText.getText().toString();
252 // Get the external private directory `File`.
253 File externalPrivateDirectoryFile = getApplicationContext().getExternalFilesDir(null);
255 // Remove the lint error below that `File` might be null.
256 assert externalPrivateDirectoryFile != null;
258 // Get the external private directory string.
259 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
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.
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);
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);
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);
291 // Get the selected export file.
292 Uri exportUri = data.getData();
294 // Remove the lint warning that the export URI might be null.
295 assert exportUri != null;
297 // Get the raw export path.
298 String rawExportPath = exportUri.getPath();
300 // Remove the warning that the raw export path might be null.
301 assert rawExportPath != null;
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);
309 // Create the export path string.
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;
319 // Everything else for the primary user should be in `/document/primary`.
320 case "/document/primary":
321 exportPath = Environment.getExternalStorageDirectory() + "/" + exportFilePath;
324 // Just in case, catch everything else and place it in the external storage directory.
326 exportPath = Environment.getExternalStorageDirectory() + "/" + exportFilePath;
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();
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);
341 // Get the selected import file.
342 Uri importUri = data.getData();
344 // Remove the lint warning that the import URI might be null.
345 assert importUri != null;
347 // Get the raw import path.
348 String rawImportPath = importUri.getPath();
350 // Remove the warning that the raw import path might be null.
351 assert rawImportPath != null;
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);
359 // Create the export path string.
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;
369 // Everything else for the primary user should be in `/document/primary`.
370 case "/document/primary":
371 importPath = Environment.getExternalStorageDirectory() + "/" + importFilePath;
374 // Just in case, catch everything else and place it in the external storage directory.
376 importPath = Environment.getExternalStorageDirectory() + "/" + importFilePath;
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();
391 public void onCloseImportExportStoragePermissionDialog(int type) {
392 // Request the storage permission based on the button that was pressed.
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);
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);
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.
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);
418 // Display an error snackbar.
419 Snackbar.make(exportFileEditText, getString(R.string.cannot_export), Snackbar.LENGTH_LONG).show();
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.
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);
432 // Display an error snackbar.
433 Snackbar.make(importFileEditText, getString(R.string.cannot_import), Snackbar.LENGTH_LONG).show();
439 private void exportSettings() {
440 // Get a handle for the export file EditText.
441 EditText exportFileEditText = findViewById(R.id.export_file_edittext);
443 // Get the export file string.
444 String exportFileString = exportFileEditText.getText().toString();
446 // Set the export file.
447 File exportFile = new File(exportFileString);
449 // Instantiate the import export database helper.
450 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
452 // Export the unencrypted file.
453 String exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, getApplicationContext());
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();
459 Snackbar.make(exportFileEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
463 private void importSettings() {
464 // Get a handle for the import file EditText.
465 EditText importFileEditText = findViewById(R.id.import_file_edittext);
467 // Get the import file string.
468 String importFileString = importFileEditText.getText().toString();
470 // Set the import file.
471 File importFile = new File(importFileString);
473 // Instantiate the import export database helper.
474 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
476 // Import the unencrypted file.
477 String importStatus = importExportDatabaseHelper.importUnencrypted(importFile, getApplicationContext());
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();
484 // Assert that the intent is not null to remove the lint error below.
485 assert restartIntent != null;
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);
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();