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