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