]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveDialog.java
0730717cabbec14a2933ec5e1fac55cf3570215b
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / SaveDialog.java
1 /*
2  * Copyright © 2019-2020 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs;
21
22 import android.Manifest;
23 import android.annotation.SuppressLint;
24 import android.app.Activity;
25 import android.app.Dialog;
26 import android.content.Context;
27 import android.content.DialogInterface;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.pm.PackageManager;
31 import android.content.res.Configuration;
32 import android.os.AsyncTask;
33 import android.os.Build;
34 import android.os.Bundle;
35 import android.os.Environment;
36 import android.provider.DocumentsContract;
37 import android.text.Editable;
38 import android.text.TextWatcher;
39 import android.view.View;
40 import android.view.WindowManager;
41 import android.widget.Button;
42 import android.widget.EditText;
43 import android.widget.TextView;
44
45 import androidx.annotation.NonNull;
46 import androidx.appcompat.app.AlertDialog;
47 import androidx.core.content.ContextCompat;
48 import androidx.fragment.app.DialogFragment;
49 import androidx.preference.PreferenceManager;
50
51 import com.stoutner.privacybrowser.R;
52 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
53 import com.stoutner.privacybrowser.asynctasks.GetUrlSize;
54 import com.stoutner.privacybrowser.helpers.DownloadLocationHelper;
55
56 import java.io.File;
57
58 public class SaveDialog extends DialogFragment {
59     // Define the save webpage listener.
60     private SaveWebpageListener saveWebpageListener;
61
62     // The public interface is used to send information back to the parent activity.
63     public interface SaveWebpageListener {
64         void onSaveWebpage(int saveType, DialogFragment dialogFragment);
65     }
66
67     // Define the get URL size AsyncTask.  This allows previous instances of the task to be cancelled if a new one is run.
68     private AsyncTask getUrlSize;
69
70     @Override
71     public void onAttach(@NonNull Context context) {
72         // Run the default commands.
73         super.onAttach(context);
74
75         // Get a handle for the save webpage listener from the launching context.
76         saveWebpageListener = (SaveWebpageListener) context;
77     }
78
79     public static SaveDialog saveUrl(int saveType, String urlString, String fileSizeString, String contentDispositionFileNameString, String userAgentString, boolean cookiesEnabled) {
80         // Create an arguments bundle.
81         Bundle argumentsBundle = new Bundle();
82
83         // Store the arguments in the bundle.
84         argumentsBundle.putInt("save_type", saveType);
85         argumentsBundle.putString("url_string", urlString);
86         argumentsBundle.putString("file_size_string", fileSizeString);
87         argumentsBundle.putString("content_disposition_file_name_string", contentDispositionFileNameString);
88         argumentsBundle.putString("user_agent_string", userAgentString);
89         argumentsBundle.putBoolean("cookies_enabled", cookiesEnabled);
90
91         // Create a new instance of the save webpage dialog.
92         SaveDialog saveWebpageDialog = new SaveDialog();
93
94         // Add the arguments bundle to the new dialog.
95         saveWebpageDialog.setArguments(argumentsBundle);
96
97         // Return the new dialog.
98         return saveWebpageDialog;
99     }
100
101     // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
102     @SuppressLint("InflateParams")
103     @Override
104     @NonNull
105     public Dialog onCreateDialog(Bundle savedInstanceState) {
106         // Get a handle for the arguments.
107         Bundle arguments = getArguments();
108
109         // Remove the incorrect lint warning that the arguments might be null.
110         assert arguments != null;
111
112         // Get the arguments from the bundle.
113         int saveType = arguments.getInt("save_type");
114         String urlString = arguments.getString("url_string");
115         String fileSizeString = arguments.getString("file_size_string");
116         String contentDispositionFileNameString = arguments.getString("content_disposition_file_name_string");
117         String userAgentString = arguments.getString("user_agent_string");
118         boolean cookiesEnabled = arguments.getBoolean("cookies_enabled");
119
120         // Get a handle for the activity and the context.
121         Activity activity = requireActivity();
122         Context context = requireContext();
123
124         // Use an alert dialog builder to create the alert dialog.
125         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialog);
126
127         // Get the current theme status.
128         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
129
130         // Set the icon according to the theme.
131         if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {  // The night theme is enabled.
132             // Set the icon according to the save type.
133             switch (saveType) {
134                 case StoragePermissionDialog.SAVE_URL:
135                     dialogBuilder.setIcon(R.drawable.copy_enabled_night);
136                     break;
137
138                 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
139                     dialogBuilder.setIcon(R.drawable.dom_storage_cleared_night);
140                     break;
141
142                 case StoragePermissionDialog.SAVE_AS_IMAGE:
143                     dialogBuilder.setIcon(R.drawable.images_enabled_night);
144                     break;
145             }
146         } else {  // The day theme is enabled.
147             // Set the icon according to the save type.
148             switch (saveType) {
149                 case StoragePermissionDialog.SAVE_URL:
150                     dialogBuilder.setIcon(R.drawable.copy_enabled_day);
151                     break;
152
153                 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
154                     dialogBuilder.setIcon(R.drawable.dom_storage_cleared_day);
155                     break;
156
157                 case StoragePermissionDialog.SAVE_AS_IMAGE:
158                     dialogBuilder.setIcon(R.drawable.images_enabled_day);
159                     break;
160             }
161         }
162
163         // Set the title according to the type.
164         switch (saveType) {
165             case StoragePermissionDialog.SAVE_URL:
166                 dialogBuilder.setTitle(R.string.save);
167                 break;
168
169             case StoragePermissionDialog.SAVE_AS_ARCHIVE:
170                 dialogBuilder.setTitle(R.string.save_archive);
171                 break;
172
173             case StoragePermissionDialog.SAVE_AS_IMAGE:
174                 dialogBuilder.setTitle(R.string.save_image);
175                 break;
176         }
177
178         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
179         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
180
181         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
182         dialogBuilder.setNegativeButton(R.string.cancel, null);
183
184         // Set the save button listener.
185         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
186             // Return the dialog fragment to the parent activity.
187             saveWebpageListener.onSaveWebpage(saveType, this);
188         });
189
190         // Create an alert dialog from the builder.
191         AlertDialog alertDialog = dialogBuilder.create();
192
193         // Remove the incorrect lint warning below that the window might be null.
194         assert alertDialog.getWindow() != null;
195
196         // Get a handle for the shared preferences.
197         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
198
199         // Get the screenshot preference.
200         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
201
202         // Disable screenshots if not allowed.
203         if (!allowScreenshots) {
204             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
205         }
206
207         // The alert dialog must be shown before items in the layout can be modified.
208         alertDialog.show();
209
210         // Get handles for the layout items.
211         EditText urlEditText = alertDialog.findViewById(R.id.url_edittext);
212         EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
213         Button browseButton = alertDialog.findViewById(R.id.browse_button);
214         TextView fileSizeTextView = alertDialog.findViewById(R.id.file_size_textview);
215         TextView fileExistsWarningTextView = alertDialog.findViewById(R.id.file_exists_warning_textview);
216         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
217         Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
218
219         // Remove the incorrect warnings that the views might be null.
220         assert urlEditText != null;
221         assert fileNameEditText != null;
222         assert browseButton != null;
223         assert fileSizeTextView != null;
224         assert fileExistsWarningTextView != null;
225         assert storagePermissionTextView != null;
226
227         // Set the file size text view.
228         fileSizeTextView.setText(fileSizeString);
229
230         // Modify the layout based on the save type.
231         if (saveType == StoragePermissionDialog.SAVE_URL) {  // A URL is being saved.
232             // Populate the URL edit text.  This must be done before the text change listener is created below so that the file size isn't requested again.
233             urlEditText.setText(urlString);
234
235             // Update the file size and the status of the save button when the URL changes.
236             urlEditText.addTextChangedListener(new TextWatcher() {
237                 @Override
238                 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
239                     // Do nothing.
240                 }
241
242                 @Override
243                 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
244                     // Do nothing.
245                 }
246
247                 @Override
248                 public void afterTextChanged(Editable editable) {
249                     // Cancel the get URL size AsyncTask if it is running.
250                     if ((getUrlSize != null)) {
251                         getUrlSize.cancel(true);
252                     }
253
254                     // Get the current URL to save.
255                     String urlToSave = urlEditText.getText().toString();
256
257                     // Wipe the file size text view.
258                     fileSizeTextView.setText("");
259
260                     // Get the file size for the current URL.
261                     getUrlSize = new GetUrlSize(context, alertDialog, userAgentString, cookiesEnabled).execute(urlToSave);
262
263                     // Enable the save button if the URL and file name are populated.
264                     saveButton.setEnabled(!urlToSave.isEmpty() && !fileNameEditText.getText().toString().isEmpty());
265                 }
266             });
267         } else {  // An archive or an image is being saved.
268             // Hide the URL edit text and the file size text view.
269             urlEditText.setVisibility(View.GONE);
270             fileSizeTextView.setVisibility(View.GONE);
271         }
272
273         // Update the status of the save button when the file name changes.
274         fileNameEditText.addTextChangedListener(new TextWatcher() {
275             @Override
276             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
277                 // Do nothing.
278             }
279
280             @Override
281             public void onTextChanged(CharSequence s, int start, int before, int count) {
282                 // Do nothing.
283             }
284
285             @Override
286             public void afterTextChanged(Editable s) {
287                 // Get the current file name.
288                 String fileNameString = fileNameEditText.getText().toString();
289
290                 // Convert the file name string to a file.
291                 File file = new File(fileNameString);
292
293                 // Check to see if the file exists.
294                 if (file.exists()) {
295                     // Show the file exists warning.
296                     fileExistsWarningTextView.setVisibility(View.VISIBLE);
297                 } else {
298                     // Hide the file exists warning.
299                     fileExistsWarningTextView.setVisibility(View.GONE);
300                 }
301
302                 // Enable the save button based on the save type.
303                 if (saveType == StoragePermissionDialog.SAVE_URL) {  // A URL is being saved.
304                     // Enable the save button if the file name and the URL is populated.
305                     saveButton.setEnabled(!fileNameString.isEmpty() && !urlEditText.getText().toString().isEmpty());
306                 } else {  // An archive or an image is being saved.
307                     // Enable the save button if the file name is populated.
308                     saveButton.setEnabled(!fileNameString.isEmpty());
309                 }
310             }
311         });
312
313         // Create a file name string.
314         String fileName = "";
315
316         // Set the file name according to the type.
317         switch (saveType) {
318             case StoragePermissionDialog.SAVE_URL:
319                 // Use the file name from the content disposition.
320                 fileName = contentDispositionFileNameString;
321                 break;
322
323             case StoragePermissionDialog.SAVE_AS_ARCHIVE:
324                 // Use an archive name ending in `.mht`.
325                 fileName = getString(R.string.webpage_mht);
326                 break;
327
328             case StoragePermissionDialog.SAVE_AS_IMAGE:
329                 // Use a file name ending in `.png`.
330                 fileName = getString(R.string.webpage_png);
331                 break;
332         }
333
334         // Save the file name as the default file name.  This must be final to be used in the lambda below.
335         final String defaultFileName = fileName;
336
337         // Instantiate the download location helper.
338         DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper();
339
340         // Get the default file path.
341         String defaultFilePath = downloadLocationHelper.getDownloadLocation(context) + "/" + defaultFileName;
342
343         // Populate the file name edit text.
344         fileNameEditText.setText(defaultFilePath);
345
346         // Move the cursor to the end of the default file path.
347         fileNameEditText.setSelection(defaultFilePath.length());
348
349         // Handle clicks on the browse button.
350         browseButton.setOnClickListener((View view) -> {
351             // Create the file picker intent.
352             Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
353
354             // Set the intent MIME type to include all files so that everything is visible.
355             browseIntent.setType("*/*");
356
357             // Set the initial file name according to the type.
358             browseIntent.putExtra(Intent.EXTRA_TITLE, defaultFileName);
359
360             // Set the initial directory if the minimum API >= 26.
361             if (Build.VERSION.SDK_INT >= 26) {
362                 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
363             }
364
365             // Request a file that can be opened.
366             browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
367
368             // Start the file picker.  This must be started under `activity` so that the request code is returned correctly.
369             activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_SAVE_WEBPAGE_REQUEST_CODE);
370         });
371
372         // Hide the storage permission text view if the permission has already been granted.
373         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
374             storagePermissionTextView.setVisibility(View.GONE);
375         }
376
377         // Return the alert dialog.
378         return alertDialog;
379     }
380 }