]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/asynctasks/SaveUrl.java
e6b811500726162066086320c13053c9869950b5
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / asynctasks / SaveUrl.java
1 /*
2  * Copyright © 2020 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.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;
33
34 import androidx.core.content.FileProvider;
35
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;
40
41 import java.io.BufferedInputStream;
42 import java.io.File;
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;
50 import java.net.URL;
51 import java.text.NumberFormat;
52
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;
57
58     // Define a success string constant.
59     private final String SUCCESS = "Success";
60
61     // Define the class variables.
62     private String filePathString;
63     private String userAgent;
64     private boolean cookiesEnabled;
65     private Snackbar savingFileSnackbar;
66
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);
72
73         // Store the class variables.
74         this.filePathString = filePathString;
75         this.userAgent = userAgent;
76         this.cookiesEnabled = cookiesEnabled;
77     }
78
79     // `onPreExecute()` operates on the UI thread.
80     @Override
81     protected void onPreExecute() {
82         // Get a handle for the activity.
83         Activity activity = activityWeakReference.get();
84
85         // Abort if the activity is gone.
86         if ((activity==null) || activity.isFinishing()) {
87             return;
88         }
89
90         // Get a handle for the no swipe view pager.
91         NoSwipeViewPager noSwipeViewPager = activity.findViewById(R.id.webviewpager);
92
93         // Create a saving file snackbar.
94         savingFileSnackbar = Snackbar.make(noSwipeViewPager, activity.getString(R.string.saving_file) + "  0% - " + filePathString, Snackbar.LENGTH_INDEFINITE);
95
96         // Display the saving file snackbar.
97         savingFileSnackbar.show();
98     }
99
100     @Override
101     protected String doInBackground(String... urlToSave) {
102         // Get handles for the context and activity.
103         Context context = contextWeakReference.get();
104         Activity activity = activityWeakReference.get();
105
106         // Abort if the activity is gone.
107         if ((activity == null) || activity.isFinishing()) {
108             return null;
109         }
110
111         // Define a save disposition string.
112         String saveDisposition = SUCCESS;
113
114         // Because everything relating to requesting data from a webserver can throw errors, the entire section must catch `IOExceptions`.
115         try {
116             // Get the URL from the calling activity.
117             URL url = new URL(urlToSave[0]);
118
119             // Instantiate the proxy helper.
120             ProxyHelper proxyHelper = new ProxyHelper();
121
122             // Get the current proxy.
123             Proxy proxy = proxyHelper.getCurrentProxy(context);
124
125             // Open a connection to the URL.  No data is actually sent at this point.
126             HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
127
128             // Add the user agent to the header property.
129             httpUrlConnection.setRequestProperty("User-Agent", userAgent);
130
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());
135
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);
140                 }
141             }
142
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.
144             try {
145                 // Get the content length header, which causes the connection to the server to be made.
146                 String contentLengthString = httpUrlConnection.getHeaderField("Content-Length");
147
148                 // Define the file size long.
149                 long fileSize;
150
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`.
157                     fileSize = -1;
158                 }
159
160                 // Get the response body stream.
161                 InputStream inputStream = new BufferedInputStream(httpUrlConnection.getInputStream());
162
163                 // Get the file.
164                 File file = new File(filePathString);
165
166                 // Delete the file if it exists.
167                 if (file.exists()) {
168                     //noinspection ResultOfMethodCallIgnored
169                     file.delete();
170                 }
171
172                 // Create a new file.
173                 //noinspection ResultOfMethodCallIgnored
174                 file.createNewFile();
175
176                 // Create an output file stream.
177                 OutputStream outputStream = new FileOutputStream(file);
178
179                 // Initialize the conversion buffer byte array.
180                 byte[] conversionBufferByteArray = new byte[1024];
181
182                 // Initialize the downloaded kilobytes counter.
183                 long downloadedKilobytesCounter = 0;
184
185                 // Define the buffer length variable.
186                 int bufferLength;
187
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);
192
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;
197
198                         publishProgress(downloadedKilobytesCounter);
199                     } else {  // The file size is known.
200                         // Update the downloaded kilobytes counter.
201                         downloadedKilobytesCounter = downloadedKilobytesCounter + bufferLength;
202
203                         // Calculate the download percentage.
204                         long downloadPercentage = (downloadedKilobytesCounter * 100) / fileSize;
205
206                         // Update the download percentage.
207                         publishProgress(downloadPercentage);
208                     }
209                 }
210
211                 // Close the input stream.
212                 inputStream.close();
213
214                 // Close the output stream.
215                 outputStream.close();
216
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);
219
220                 // Add the URI to the media scanner intent.
221                 mediaScannerIntent.setData(Uri.fromFile(file));
222
223                 // Make it so.
224                 activity.sendBroadcast(mediaScannerIntent);
225             } finally {
226                 // Disconnect the HTTP URL connection.
227                 httpUrlConnection.disconnect();
228             }
229         } catch (IOException exception) {
230             // Store the error in the save disposition string.
231             saveDisposition = exception.toString();
232         }
233
234         // Return the save disposition string.
235         return saveDisposition;
236     }
237
238     // `onProgressUpdate()` operates on the UI thread.
239     @Override
240     protected void onProgressUpdate(Long... downloadPercentage) {
241         // Get a handle for the activity.
242         Activity activity = activityWeakReference.get();
243
244         // Abort if the activity is gone.
245         if ((activity == null) || activity.isFinishing()) {
246             return;
247         }
248
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];
253
254             // Format the number of bytes downloaded.
255             String formattedNumberOfBytesDownloaded = NumberFormat.getInstance().format(numberOfBytesDownloaded);
256
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);
262         }
263     }
264
265     // `onPostExecute()` operates on the UI thread.
266     @Override
267     protected void onPostExecute(String saveDisposition) {
268         // Get handles for the context and activity.
269         Context context = contextWeakReference.get();
270         Activity activity = activityWeakReference.get();
271
272         // Abort if the activity is gone.
273         if ((activity == null) || activity.isFinishing()) {
274             return;
275         }
276
277         // Get a handle for the no swipe view pager.
278         NoSwipeViewPager noSwipeViewPager = activity.findViewById(R.id.webviewpager);
279
280         // Dismiss the saving file snackbar.
281         savingFileSnackbar.dismiss();
282
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);
287
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);
293
294                     // Define a file URI variable
295                     Uri fileUri;
296
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);
302                     }
303
304                     // Get a handle for the content resolver.
305                     ContentResolver contentResolver = context.getContentResolver();
306
307                     // Create an open intent with `ACTION_VIEW`.
308                     Intent openIntent = new Intent(Intent.ACTION_VIEW);
309
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));
315                     }
316
317                     // Allow the app to read the file URI.
318                     openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
319
320                     // Try the intent.
321                     try {
322                         // Show the chooser.
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();
327                     }
328                 });
329             }
330
331             // Show the file saved snackbar.
332             fileSavedSnackbar.show();
333         } else {
334             // Display the file saving error.
335             Snackbar.make(noSwipeViewPager, activity.getString(R.string.error_saving_file) + "  " + saveDisposition, Snackbar.LENGTH_INDEFINITE).show();
336         }
337     }
338 }