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