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