]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/asynctasks/SaveUrl.java
Fix downloads consuming massive CPU and locking the UI on slower CPUs. https://redmin...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / asynctasks / SaveUrl.java
1 /*
2  * Copyright © 2020-2021 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.asynctasks;
21
22 import android.app.Activity;
23 import android.content.Context;
24 import android.net.Uri;
25 import android.os.AsyncTask;
26 import android.util.Base64;
27 import android.webkit.CookieManager;
28
29 import com.google.android.material.snackbar.Snackbar;
30 import com.stoutner.privacybrowser.R;
31 import com.stoutner.privacybrowser.helpers.ProxyHelper;
32 import com.stoutner.privacybrowser.views.NoSwipeViewPager;
33
34 import java.io.BufferedInputStream;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.lang.ref.WeakReference;
38 import java.net.HttpURLConnection;
39 import java.net.Proxy;
40 import java.net.URL;
41 import java.text.NumberFormat;
42
43 public class SaveUrl extends AsyncTask<String, Long, String> {
44     // Define a weak references.
45     private final WeakReference<Context> contextWeakReference;
46     private final WeakReference<Activity> activityWeakReference;
47
48     // Define a success string constant.
49     private final String SUCCESS = "Success";
50
51     // Define the class variables.
52     private final String filePathString;
53     private final String userAgent;
54     private final boolean cookiesEnabled;
55     private Snackbar savingFileSnackbar;
56     private long fileSize;
57     private String formattedFileSize;
58     private String urlString = "";
59
60     // The public constructor.
61     public SaveUrl(Context context, Activity activity, String filePathString, String userAgent, boolean cookiesEnabled) {
62         // Populate weak references to the calling context and activity.
63         contextWeakReference = new WeakReference<>(context);
64         activityWeakReference = new WeakReference<>(activity);
65
66         // Store the class variables.
67         this.filePathString = filePathString;
68         this.userAgent = userAgent;
69         this.cookiesEnabled = cookiesEnabled;
70     }
71
72     // `onPreExecute()` operates on the UI thread.
73     @Override
74     protected void onPreExecute() {
75         // Get a handle for the activity.
76         Activity activity = activityWeakReference.get();
77
78         // Abort if the activity is gone.
79         if ((activity==null) || activity.isFinishing()) {
80             return;
81         }
82
83         // Get a handle for the no swipe view pager.
84         NoSwipeViewPager noSwipeViewPager = activity.findViewById(R.id.webviewpager);
85
86         // Create a saving file snackbar.
87         savingFileSnackbar = Snackbar.make(noSwipeViewPager, activity.getString(R.string.saving_file) + "  0%  -  " + urlString, Snackbar.LENGTH_INDEFINITE);
88
89         // Display the saving file snackbar.
90         savingFileSnackbar.show();
91     }
92
93     @Override
94     protected String doInBackground(String... urlToSave) {
95         // Get handles for the context and activity.
96         Context context = contextWeakReference.get();
97         Activity activity = activityWeakReference.get();
98
99         // Abort if the activity is gone.
100         if ((activity == null) || activity.isFinishing()) {
101             return null;
102         }
103
104         // Define a save disposition string.
105         String saveDisposition = SUCCESS;
106
107         // Get the URL string.
108         urlString = urlToSave[0];
109
110         try {
111             // Open an output stream.
112             OutputStream outputStream = activity.getContentResolver().openOutputStream(Uri.parse(filePathString));
113
114             // Save the URL.
115             if (urlString.startsWith("data:")) {  // The URL contains the entire data of an image.
116                 // Get the Base64 data, which begins after a `,`.
117                 String base64DataString = urlString.substring(urlString.indexOf(",") + 1);
118
119                 // Decode the Base64 string to a byte array.
120                 byte[] base64DecodedDataByteArray = Base64.decode(base64DataString, Base64.DEFAULT);
121
122                 // Write the Base64 byte array to the output stream.
123                 outputStream.write(base64DecodedDataByteArray);
124             } else {  // The URL points to the data location on the internet.
125                 // Get the URL from the calling activity.
126                 URL url = new URL(urlString);
127
128                 // Instantiate the proxy helper.
129                 ProxyHelper proxyHelper = new ProxyHelper();
130
131                 // Get the current proxy.
132                 Proxy proxy = proxyHelper.getCurrentProxy(context);
133
134                 // Open a connection to the URL.  No data is actually sent at this point.
135                 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
136
137                 // Add the user agent to the header property.
138                 httpUrlConnection.setRequestProperty("User-Agent", userAgent);
139
140                 // Add the cookies if they are enabled.
141                 if (cookiesEnabled) {
142                     // Get the cookies for the current domain.
143                     String cookiesString = CookieManager.getInstance().getCookie(url.toString());
144
145                     // Only add the cookies if they are not null.
146                     if (cookiesString != null) {
147                         // Add the cookies to the header property.
148                         httpUrlConnection.setRequestProperty("Cookie", cookiesString);
149                     }
150                 }
151
152                 // The actual network request is in a `try` bracket so that `disconnect()` is run in the `finally` section even if an error is encountered in the main block.
153                 try {
154                     // Get the content length header, which causes the connection to the server to be made.
155                     String contentLengthString = httpUrlConnection.getHeaderField("Content-Length");
156
157                     // Make sure the content length isn't null.
158                     if (contentLengthString != null) {  // The content length isn't null.
159                         // Convert the content length to an long.
160                         fileSize = Long.parseLong(contentLengthString);
161
162                         // Format the file size for display.
163                         formattedFileSize = NumberFormat.getInstance().format(fileSize);
164                     } else {  // The content length is null.
165                         // Set the file size to be `-1`.
166                         fileSize = -1;
167                     }
168
169                     // Get the response body stream.
170                     InputStream inputStream = new BufferedInputStream(httpUrlConnection.getInputStream());
171
172                     // Initialize the conversion buffer byte array.
173                     // This is set to a megabyte so that frequent updating of the snackbar doesn't freeze the interface on download.  <https://redmine.stoutner.com/issues/709>
174                     byte[] conversionBufferByteArray = new byte[1048576];
175
176                     // Initialize the downloaded kilobytes counter.
177                     long downloadedKilobytesCounter = 0;
178
179                     // Define the buffer length variable.
180                     int bufferLength;
181
182                     // Attempt to read data from the input stream and store it in the output stream.  Also store the amount of data read in the buffer length variable.
183                     while ((bufferLength = inputStream.read(conversionBufferByteArray)) > 0) {  // Proceed while the amount of data stored in the buffer in > 0.
184                         // Write the contents of the conversion buffer to the file output stream.
185                         outputStream.write(conversionBufferByteArray, 0, bufferLength);
186
187                         // Update the downloaded kilobytes counter.
188                         downloadedKilobytesCounter = downloadedKilobytesCounter + bufferLength;
189
190                         // Update the file download progress snackbar.
191                         publishProgress(downloadedKilobytesCounter);
192                     }
193
194                     // Close the input stream.
195                     inputStream.close();
196                 } finally {
197                     // Disconnect the HTTP URL connection.
198                     httpUrlConnection.disconnect();
199                 }
200             }
201
202             // Close the output stream.
203             outputStream.close();
204         } catch (Exception exception) {
205             // Store the error in the save disposition string.
206             saveDisposition = exception.toString();
207         }
208
209         // Return the save disposition string.
210         return saveDisposition;
211     }
212
213     // `onProgressUpdate()` operates on the UI thread.
214     @Override
215     protected void onProgressUpdate(Long... numberOfBytesDownloaded) {
216         // Get a handle for the activity.
217         Activity activity = activityWeakReference.get();
218
219         // Abort if the activity is gone.
220         if ((activity == null) || activity.isFinishing()) {
221             return;
222         }
223
224         // Format the number of bytes downloaded.
225         String formattedNumberOfBytesDownloaded = NumberFormat.getInstance().format(numberOfBytesDownloaded[0]);
226
227         // Check to see if the file size is known.
228         if (fileSize == -1) {  // The size of the download file is not known.
229             // Update the snackbar.
230             savingFileSnackbar.setText(activity.getString(R.string.saving_file) + "  " + formattedNumberOfBytesDownloaded + " " + activity.getString(R.string.bytes) + "  -  " + urlString);
231         } else {  // The size of the download file is known.
232             // Calculate the download percentage.
233             long downloadPercentage = (numberOfBytesDownloaded[0] * 100) / fileSize;
234
235             // Update the snackbar.
236             savingFileSnackbar.setText(activity.getString(R.string.saving_file) + "  " + downloadPercentage + "%  -  " + formattedNumberOfBytesDownloaded + " " + activity.getString(R.string.bytes) + " / " + formattedFileSize + " " +
237                     activity.getString(R.string.bytes) + "  -  " + urlString);
238         }
239     }
240
241     // `onPostExecute()` operates on the UI thread.
242     @Override
243     protected void onPostExecute(String saveDisposition) {
244         // Get handles for the context and activity.
245         Activity activity = activityWeakReference.get();
246
247         // Abort if the activity is gone.
248         if ((activity == null) || activity.isFinishing()) {
249             return;
250         }
251
252         // Get a handle for the no swipe view pager.
253         NoSwipeViewPager noSwipeViewPager = activity.findViewById(R.id.webviewpager);
254
255         // Dismiss the saving file snackbar.
256         savingFileSnackbar.dismiss();
257
258         // Display a save disposition snackbar.
259         if (saveDisposition.equals(SUCCESS)) {
260             // Display the file saved snackbar.
261             Snackbar.make(noSwipeViewPager, activity.getString(R.string.file_saved) + "  " + urlString, Snackbar.LENGTH_LONG).show();
262         } else {
263             // Display the file saving error.
264             Snackbar.make(noSwipeViewPager, activity.getString(R.string.error_saving_file) + "  " + saveDisposition, Snackbar.LENGTH_INDEFINITE).show();
265         }
266     }
267 }