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