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