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.Context;
24 import android.os.AsyncTask;
25 import android.webkit.CookieManager;
27 import com.google.android.material.snackbar.Snackbar;
28 import com.stoutner.privacybrowser.R;
29 import com.stoutner.privacybrowser.helpers.ProxyHelper;
30 import com.stoutner.privacybrowser.views.NoSwipeViewPager;
32 import java.io.BufferedInputStream;
34 import java.io.FileOutputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.OutputStream;
38 import java.lang.ref.WeakReference;
39 import java.net.HttpURLConnection;
40 import java.net.Proxy;
43 public class SaveUrl extends AsyncTask<String, Void, String> {
44 // Define a weak references for the calling context and activities.
45 private WeakReference<Context> contextWeakReference;
46 private WeakReference<Activity> activityWeakReference;
48 // Define a success string constant.
49 private final String SUCCESS = "Success";
51 // Define the class variables.
52 private String filePathString;
53 private String userAgent;
54 private boolean cookiesEnabled;
55 private Snackbar savingFileSnackbar;
57 // The public constructor.
58 public SaveUrl(Context context, Activity activity, String filePathString, String userAgent, boolean cookiesEnabled) {
59 // Populate weak references to the calling context and activity.
60 contextWeakReference = new WeakReference<>(context);
61 activityWeakReference = new WeakReference<>(activity);
63 // Store the class variables.
64 this.filePathString = filePathString;
65 this.userAgent = userAgent;
66 this.cookiesEnabled = cookiesEnabled;
69 // `onPreExecute()` operates on the UI thread.
71 protected void onPreExecute() {
72 // Get a handle for the activity.
73 Activity activity = activityWeakReference.get();
75 // Abort if the activity is gone.
76 if ((activity==null) || activity.isFinishing()) {
80 // Get a handle for the no swipe view pager.
81 NoSwipeViewPager noSwipeViewPager = activity.findViewById(R.id.webviewpager);
83 // Create a saving file snackbar.
84 savingFileSnackbar = Snackbar.make(noSwipeViewPager, R.string.saving_file, Snackbar.LENGTH_INDEFINITE);
86 // Display the saving file snackbar.
87 savingFileSnackbar.show();
91 protected String doInBackground(String... urlToSave) {
92 // Get a handle for the context and activity.
93 Context context = contextWeakReference.get();
94 Activity activity = activityWeakReference.get();
96 // Abort if the activity is gone.
97 if ((activity == null) || activity.isFinishing()) {
101 // Define a save disposition string.
102 String saveDisposition = SUCCESS;
104 // Because everything relating to requesting data from a webserver can throw errors, the entire section must catch `IOExceptions`.
106 // Get the URL from the main activity.
107 URL url = new URL(urlToSave[0]);
109 // Instantiate the proxy helper.
110 ProxyHelper proxyHelper = new ProxyHelper();
112 // Get the current proxy.
113 Proxy proxy = proxyHelper.getCurrentProxy(context);
115 // Open a connection to the URL. No data is actually sent at this point.
116 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
118 // Add the user agent to the header property.
119 httpUrlConnection.setRequestProperty("User-Agent", userAgent);
121 // Add the cookies if they are enabled.
122 if (cookiesEnabled) {
123 // Get the cookies for the current domain.
124 String cookiesString = CookieManager.getInstance().getCookie(url.toString());
126 // Only add the cookies if they are not null.
127 if (cookiesString != null) {
128 // Add the cookies to the header property.
129 httpUrlConnection.setRequestProperty("Cookie", cookiesString);
133 // 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.
135 // Get the response code, which causes the connection to the server to be made.
136 httpUrlConnection.getResponseCode();
138 // Get the response body stream.
139 InputStream inputStream = new BufferedInputStream(httpUrlConnection.getInputStream());
142 File file = new File(filePathString);
144 // Delete the file if it exists.
146 //noinspection ResultOfMethodCallIgnored
150 // Create a new file.
151 //noinspection ResultOfMethodCallIgnored
152 file.createNewFile();
154 // Create an output file stream.
155 OutputStream outputStream = new FileOutputStream(file);
157 // Initialize the conversion buffer byte array.
158 byte[] conversionBufferByteArray = new byte[1024];
160 // Define the buffer length variable.
163 // 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.
164 while ((bufferLength = inputStream.read(conversionBufferByteArray)) > 0) { // Proceed while the amount of data stored in the buffer in > 0.
165 // Write the contents of the conversion buffer to the output stream.
166 outputStream.write(conversionBufferByteArray, 0, bufferLength);
169 // Close the input stream.
172 // Close the output stream.
173 outputStream.close();
175 // Disconnect the HTTP URL connection.
176 httpUrlConnection.disconnect();
178 } catch (IOException exception) {
179 // Store the error in the save disposition string.
180 saveDisposition = exception.toString();
183 // Return the save disposition string.
184 return saveDisposition;
187 // `onPostExecute()` operates on the UI thread.
189 protected void onPostExecute(String saveDisposition) {
190 // Get a handle for the activity.
191 Activity activity = activityWeakReference.get();
193 // Abort if the activity is gone.
194 if ((activity == null) || activity.isFinishing()) {
198 // Get a handle for the no swipe view pager.
199 NoSwipeViewPager noSwipeViewPager = activity.findViewById(R.id.webviewpager);
201 // Dismiss the saving file snackbar.
202 savingFileSnackbar.dismiss();
204 // Display a save disposition snackbar.
205 if (saveDisposition.equals(SUCCESS)) {
206 Snackbar.make(noSwipeViewPager, R.string.file_saved, Snackbar.LENGTH_SHORT).show();
208 Snackbar.make(noSwipeViewPager, activity.getString(R.string.error_saving_file) + " " + saveDisposition, Snackbar.LENGTH_INDEFINITE).show();