]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/DownloadFileDialog.java
Make first-party cookies tab aware.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / DownloadFileDialog.java
1 /*
2  * Copyright © 2016-2019 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.annotation.SuppressLint;
23 import android.app.AlertDialog;
24 import android.app.Dialog;
25 import android.content.Context;
26 import android.content.DialogInterface;
27 import android.content.SharedPreferences;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.preference.PreferenceManager;
31 import android.view.KeyEvent;
32 import android.view.LayoutInflater;
33 import android.view.View;
34 import android.view.WindowManager;
35 import android.widget.EditText;
36 import android.widget.TextView;
37
38 import androidx.annotation.NonNull;
39 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
40
41 import com.stoutner.privacybrowser.R;
42
43 import java.util.Locale;
44
45 public class DownloadFileDialog extends DialogFragment {
46     // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
47     private DownloadFileListener downloadFileListener;
48
49     // The public interface is used to send information back to the parent activity.
50     public interface DownloadFileListener {
51         void onDownloadFile(DialogFragment dialogFragment, String downloadUrl);
52     }
53
54     @Override
55     public void onAttach(Context context) {
56         // Run the default commands.
57         super.onAttach(context);
58
59         // Get a handle for `DownloadFileListener` from the launching context.
60         downloadFileListener = (DownloadFileListener) context;
61     }
62
63     public static DownloadFileDialog fromUrl(String urlString, String contentDisposition, long contentLength) {
64         // Create an arguments bundle.
65         Bundle argumentsBundle = new Bundle();
66
67         // Create a variable for the file name string.
68         String fileNameString;
69
70         // Parse the filename from `contentDisposition`.
71         if (contentDisposition.contains("filename=\"")) {  // The file name is contained in a string surrounded by `""`.
72             fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
73         } else if (contentDisposition.contains("filename=") && ((contentDisposition.indexOf(";", contentDisposition.indexOf("filename=") + 9)) > 0 )) {
74             // The file name is contained in a string beginning with `filename=` and ending with `;`.
75             fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.indexOf(";", contentDisposition.indexOf("filename=") + 9));
76         } else if (contentDisposition.contains("filename=")) {  // The file name is contained in a string beginning with `filename=` and proceeding to the end of `contentDisposition`.
77             fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9);
78         } else {  // `contentDisposition` does not contain the filename, so use the last path segment of the URL.
79             Uri downloadUri = Uri.parse(urlString);
80             fileNameString = downloadUri.getLastPathSegment();
81         }
82
83         // Store the variables in the bundle.
84         argumentsBundle.putString("URL", urlString);
85         argumentsBundle.putString("File_Name", fileNameString);
86         argumentsBundle.putLong("File_Size", contentLength);
87
88         // Add the arguments bundle to this instance of `DownloadFileDialog`.
89         DownloadFileDialog thisDownloadFileDialog = new DownloadFileDialog();
90         thisDownloadFileDialog.setArguments(argumentsBundle);
91         return thisDownloadFileDialog;
92     }
93
94     @Override
95     @NonNull
96     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
97     @SuppressLint("InflateParams")
98     public Dialog onCreateDialog(Bundle savedInstanceState) {
99         // Remove the warning below that `getArguments()` might be null.
100         assert getArguments() != null;
101
102         // Store the variables from the bundle.
103         String downloadUrl = getArguments().getString("URL");
104         String downloadFileName = getArguments().getString("File_Name");
105         long fileSizeLong = getArguments().getLong("File_Size");
106
107         // Initialize the file size string.
108         String fileSize;
109
110         // Convert `fileSizeLong` to a String.
111         if (fileSizeLong == -1) {  // We don't know the file size.
112             fileSize = getString(R.string.unknown_size);
113         } else {  // Convert `fileSize` to MB and store it in `fileSizeString`.  `%.3g` displays the three most significant digits.
114             fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
115         }
116
117         // Remove the warning below that `getActivity()` might be null;
118         assert getActivity() != null;
119
120         // Get the activity's layout inflater.
121         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
122
123         // Use an alert dialog builder to create the alert dialog.
124         AlertDialog.Builder dialogBuilder;
125
126         // Get a handle for the shared preferences.
127         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
128
129         // Get the screenshot and theme preferences.
130         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
131         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
132
133         // Set the style according to the theme.
134         if (darkTheme) {
135             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
136         } else {
137             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
138         }
139
140         // Set the title.
141         dialogBuilder.setTitle(R.string.save_as);
142
143         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
144         dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
145
146         // Set an listener on the negative button.
147         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
148             // Do nothing if `Cancel` is clicked.  The `Dialog` will automatically close.
149         });
150
151         // Set an listener on the positive button
152         dialogBuilder.setPositiveButton(R.string.download, (DialogInterface dialog, int which) -> {
153             // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
154             downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
155         });
156
157         // Create an alert dialog from the alert dialog builder`.
158         final AlertDialog alertDialog = dialogBuilder.create();
159
160         // Remove the warning below that `getWindow()` might be null.
161         assert alertDialog.getWindow() != null;
162
163         // Disable screenshots if not allowed.
164         if (!allowScreenshots) {
165             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
166         }
167
168         // Show the keyboard when alert dialog is displayed on the screen.
169         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
170
171         // We need to show `alertDialog` before we can modify the contents.
172         alertDialog.show();
173
174         // Set the text for `downloadFileSizeTextView`.
175         TextView downloadFileSizeTextView = alertDialog.findViewById(R.id.download_file_size);
176         downloadFileSizeTextView.setText(fileSize);
177
178         // Set the text for `downloadFileNameTextView`.
179         EditText downloadFileNameTextView = alertDialog.findViewById(R.id.download_file_name);
180         downloadFileNameTextView.setText(downloadFileName);
181
182         // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
183         downloadFileNameTextView.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
184             // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
185             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
186                 // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
187                 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
188
189                 // Manually dismiss the alert dialog.
190                 alertDialog.dismiss();
191
192                 // Consume the event.
193                 return true;
194             } else {  // If any other key was pressed, do not consume the event.
195                 return false;
196             }
197         });
198
199         // `onCreateDialog` requires the return of an `AlertDialog`.
200         return alertDialog;
201     }
202 }