2 * Copyright © 2020 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.asynctasks;
22 import android.app.Activity;
23 import android.content.ActivityNotFoundException;
24 import android.content.ContentResolver;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.net.Uri;
28 import android.os.AsyncTask;
29 import android.os.Build;
30 import android.view.View;
31 import android.webkit.CookieManager;
32 import android.webkit.MimeTypeMap;
34 import androidx.core.content.FileProvider;
36 import com.google.android.material.snackbar.Snackbar;
37 import com.stoutner.privacybrowser.R;
38 import com.stoutner.privacybrowser.helpers.ProxyHelper;
39 import com.stoutner.privacybrowser.views.NoSwipeViewPager;
41 import java.io.BufferedInputStream;
43 import java.io.FileOutputStream;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.io.OutputStream;
47 import java.lang.ref.WeakReference;
48 import java.net.HttpURLConnection;
49 import java.net.Proxy;
51 import java.text.NumberFormat;
53 public class SaveUrl extends AsyncTask<String, Long, String> {
54 // Define a weak references for the calling context and activity.
55 private WeakReference<Context> contextWeakReference;
56 private WeakReference<Activity> activityWeakReference;
58 // Define a success string constant.
59 private final String SUCCESS = "Success";
61 // Define the class variables.
62 private String filePathString;
63 private String userAgent;
64 private boolean cookiesEnabled;
65 private Snackbar savingFileSnackbar;
67 // The public constructor.
68 public SaveUrl(Context context, Activity activity, String filePathString, String userAgent, boolean cookiesEnabled) {
69 // Populate weak references to the calling context and activity.
70 contextWeakReference = new WeakReference<>(context);
71 activityWeakReference = new WeakReference<>(activity);
73 // Store the class variables.
74 this.filePathString = filePathString;
75 this.userAgent = userAgent;
76 this.cookiesEnabled = cookiesEnabled;
79 // `onPreExecute()` operates on the UI thread.
81 protected void onPreExecute() {
82 // Get a handle for the activity.
83 Activity activity = activityWeakReference.get();
85 // Abort if the activity is gone.
86 if ((activity==null) || activity.isFinishing()) {
90 // Get a handle for the no swipe view pager.
91 NoSwipeViewPager noSwipeViewPager = activity.findViewById(R.id.webviewpager);
93 // Create a saving file snackbar.
94 savingFileSnackbar = Snackbar.make(noSwipeViewPager, activity.getString(R.string.saving_file) + " 0% - " + filePathString, Snackbar.LENGTH_INDEFINITE);
96 // Display the saving file snackbar.
97 savingFileSnackbar.show();
101 protected String doInBackground(String... urlToSave) {
102 // Get handles for the context and activity.
103 Context context = contextWeakReference.get();
104 Activity activity = activityWeakReference.get();
106 // Abort if the activity is gone.
107 if ((activity == null) || activity.isFinishing()) {
111 // Define a save disposition string.
112 String saveDisposition = SUCCESS;
114 // Because everything relating to requesting data from a webserver can throw errors, the entire section must catch `IOExceptions`.
116 // Get the URL from the calling activity.
117 URL url = new URL(urlToSave[0]);
119 // Instantiate the proxy helper.
120 ProxyHelper proxyHelper = new ProxyHelper();
122 // Get the current proxy.
123 Proxy proxy = proxyHelper.getCurrentProxy(context);
125 // Open a connection to the URL. No data is actually sent at this point.
126 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
128 // Add the user agent to the header property.
129 httpUrlConnection.setRequestProperty("User-Agent", userAgent);
131 // Add the cookies if they are enabled.
132 if (cookiesEnabled) {
133 // Get the cookies for the current domain.
134 String cookiesString = CookieManager.getInstance().getCookie(url.toString());
136 // Only add the cookies if they are not null.
137 if (cookiesString != null) {
138 // Add the cookies to the header property.
139 httpUrlConnection.setRequestProperty("Cookie", cookiesString);
143 // 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.
145 // Get the content length header, which causes the connection to the server to be made.
146 String contentLengthString = httpUrlConnection.getHeaderField("Content-Length");
148 // Define the file size long.
151 // Make sure the content length isn't null.
152 if (contentLengthString != null) { // The content length isn't null.
153 // Convert the content length to an long.
154 fileSize = Long.parseLong(contentLengthString);
155 } else { // The content length is null.
156 // Set the file size to be `-1`.
160 // Get the response body stream.
161 InputStream inputStream = new BufferedInputStream(httpUrlConnection.getInputStream());
164 File file = new File(filePathString);
166 // Delete the file if it exists.
168 //noinspection ResultOfMethodCallIgnored
172 // Create a new file.
173 //noinspection ResultOfMethodCallIgnored
174 file.createNewFile();
176 // Create an output file stream.
177 OutputStream outputStream = new FileOutputStream(file);
179 // Initialize the conversion buffer byte array.
180 byte[] conversionBufferByteArray = new byte[1024];
182 // Initialize the downloaded kilobytes counter.
183 long downloadedKilobytesCounter = 0;
185 // Define the buffer length variable.
188 // 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.
189 while ((bufferLength = inputStream.read(conversionBufferByteArray)) > 0) { // Proceed while the amount of data stored in the buffer in > 0.
190 // Write the contents of the conversion buffer to the output stream.
191 outputStream.write(conversionBufferByteArray, 0, bufferLength);
193 // Update the file download progress snackbar.
194 if (fileSize == -1) { // The file size is unknown.
195 // Negatively update the downloaded kilobytes counter.
196 downloadedKilobytesCounter = downloadedKilobytesCounter - bufferLength;
198 publishProgress(downloadedKilobytesCounter);
199 } else { // The file size is known.
200 // Update the downloaded kilobytes counter.
201 downloadedKilobytesCounter = downloadedKilobytesCounter + bufferLength;
203 // Calculate the download percentage.
204 long downloadPercentage = (downloadedKilobytesCounter * 100) / fileSize;
206 // Update the download percentage.
207 publishProgress(downloadPercentage);
211 // Close the input stream.
214 // Close the output stream.
215 outputStream.close();
217 // Define a media scanner intent, which adds items like pictures to Android's recent file list.
218 Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
220 // Add the URI to the media scanner intent.
221 mediaScannerIntent.setData(Uri.fromFile(file));
224 activity.sendBroadcast(mediaScannerIntent);
226 // Disconnect the HTTP URL connection.
227 httpUrlConnection.disconnect();
229 } catch (IOException exception) {
230 // Store the error in the save disposition string.
231 saveDisposition = exception.toString();
234 // Return the save disposition string.
235 return saveDisposition;
238 // `onProgressUpdate()` operates on the UI thread.
240 protected void onProgressUpdate(Long... downloadPercentage) {
241 // Get a handle for the activity.
242 Activity activity = activityWeakReference.get();
244 // Abort if the activity is gone.
245 if ((activity == null) || activity.isFinishing()) {
249 // Check to see if a download percentage has been calculated.
250 if (downloadPercentage[0] < 0) { // There is no download percentage. The negative number represents the raw downloaded kilobytes.
251 // Calculate the number of bytes downloaded. When the `downloadPercentage` is negative, it is actually the raw number of kilobytes downloaded.
252 long numberOfBytesDownloaded = 0 - downloadPercentage[0];
254 // Format the number of bytes downloaded.
255 String formattedNumberOfBytesDownloaded = NumberFormat.getInstance().format(numberOfBytesDownloaded);
257 // Update the snackbar.
258 savingFileSnackbar.setText(activity.getString(R.string.saving_file) + " " + formattedNumberOfBytesDownloaded + " " + activity.getString(R.string.bytes) + " - " + filePathString);
259 } else { // There is a download percentage.
260 // Update the snackbar.
261 savingFileSnackbar.setText(activity.getString(R.string.saving_file) + " " + downloadPercentage[0] + "% - " + filePathString);
265 // `onPostExecute()` operates on the UI thread.
267 protected void onPostExecute(String saveDisposition) {
268 // Get handles for the context and activity.
269 Context context = contextWeakReference.get();
270 Activity activity = activityWeakReference.get();
272 // Abort if the activity is gone.
273 if ((activity == null) || activity.isFinishing()) {
277 // Get a handle for the no swipe view pager.
278 NoSwipeViewPager noSwipeViewPager = activity.findViewById(R.id.webviewpager);
280 // Dismiss the saving file snackbar.
281 savingFileSnackbar.dismiss();
283 // Display a save disposition snackbar.
284 if (saveDisposition.equals(SUCCESS)) {
285 // Create a file saved snackbar.
286 Snackbar fileSavedSnackbar = Snackbar.make(noSwipeViewPager, activity.getString(R.string.file_saved) + " " + filePathString, Snackbar.LENGTH_LONG);
288 // Add an open action if the file is not an APK on API >= 26 (that scenario requires the REQUEST_INSTALL_PACKAGES permission).
289 if (!(Build.VERSION.SDK_INT >= 26 && filePathString.endsWith(".apk"))) {
290 fileSavedSnackbar.setAction(R.string.open, (View v) -> {
291 // Get a file for the file path string.
292 File file = new File(filePathString);
294 // Define a file URI variable
297 // Get the URI for the file according to the Android version.
298 if (Build.VERSION.SDK_INT >= 24) { // Use a file provider.
299 fileUri = FileProvider.getUriForFile(context, activity.getString(R.string.file_provider), file);
300 } else { // Get the raw file path URI.
301 fileUri = Uri.fromFile(file);
304 // Get a handle for the content resolver.
305 ContentResolver contentResolver = context.getContentResolver();
307 // Create an open intent with `ACTION_VIEW`.
308 Intent openIntent = new Intent(Intent.ACTION_VIEW);
310 // Set the URI and the MIME type.
311 if (filePathString.endsWith("apk") || filePathString.endsWith("APK")) { // Force detection of APKs.
312 openIntent.setDataAndType(fileUri, MimeTypeMap.getSingleton().getMimeTypeFromExtension("apk"));
313 } else { // Autodetect the MIME type.
314 openIntent.setDataAndType(fileUri, contentResolver.getType(fileUri));
317 // Allow the app to read the file URI.
318 openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
323 activity.startActivity(openIntent);
324 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
325 // Show a snackbar with the error.
326 Snackbar.make(noSwipeViewPager, activity.getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
331 // Show the file saved snackbar.
332 fileSavedSnackbar.show();
334 // Display the file saving error.
335 Snackbar.make(noSwipeViewPager, activity.getString(R.string.error_saving_file) + " " + saveDisposition, Snackbar.LENGTH_INDEFINITE).show();