HttpDownloadConnection.java

  1package eu.siacs.conversations.http;
  2
  3import android.content.Intent;
  4import android.net.Uri;
  5import android.os.PowerManager;
  6import android.util.Log;
  7
  8import java.io.BufferedInputStream;
  9import java.io.IOException;
 10import java.io.InputStream;
 11import java.io.OutputStream;
 12import java.net.HttpURLConnection;
 13import java.net.InetAddress;
 14import java.net.InetSocketAddress;
 15import java.net.MalformedURLException;
 16import java.net.Proxy;
 17import java.net.URL;
 18import java.util.Arrays;
 19import java.util.concurrent.CancellationException;
 20
 21import javax.net.ssl.HttpsURLConnection;
 22import javax.net.ssl.SSLHandshakeException;
 23
 24import eu.siacs.conversations.Config;
 25import eu.siacs.conversations.R;
 26import eu.siacs.conversations.entities.DownloadableFile;
 27import eu.siacs.conversations.entities.Message;
 28import eu.siacs.conversations.entities.Transferable;
 29import eu.siacs.conversations.entities.TransferablePlaceholder;
 30import eu.siacs.conversations.persistance.FileBackend;
 31import eu.siacs.conversations.services.AbstractConnectionManager;
 32import eu.siacs.conversations.services.XmppConnectionService;
 33import eu.siacs.conversations.utils.CryptoHelper;
 34
 35public class HttpDownloadConnection implements Transferable {
 36
 37	private HttpConnectionManager mHttpConnectionManager;
 38	private XmppConnectionService mXmppConnectionService;
 39
 40	private URL mUrl;
 41	private Message message;
 42	private DownloadableFile file;
 43	private int mStatus = Transferable.STATUS_UNKNOWN;
 44	private boolean acceptedAutomatically = false;
 45	private int mProgress = 0;
 46	private boolean mUseTor = false;
 47	private boolean canceled = false;
 48
 49	public HttpDownloadConnection(HttpConnectionManager manager) {
 50		this.mHttpConnectionManager = manager;
 51		this.mXmppConnectionService = manager.getXmppConnectionService();
 52		this.mUseTor = mXmppConnectionService.useTorToConnect();
 53	}
 54
 55	@Override
 56	public boolean start() {
 57		if (mXmppConnectionService.hasInternetConnection()) {
 58			if (this.mStatus == STATUS_OFFER_CHECK_FILESIZE) {
 59				checkFileSize(true);
 60			} else {
 61				new Thread(new FileDownloader(true)).start();
 62			}
 63			return true;
 64		} else {
 65			return false;
 66		}
 67	}
 68
 69	public void init(Message message) {
 70		init(message, false);
 71	}
 72
 73	public void init(Message message, boolean interactive) {
 74		this.message = message;
 75		this.message.setTransferable(this);
 76		try {
 77			if (message.hasFileOnRemoteHost()) {
 78				mUrl = message.getFileParams().url;
 79			} else {
 80				mUrl = new URL(message.getBody());
 81			}
 82			String[] parts = mUrl.getPath().toLowerCase().split("\\.");
 83			String lastPart = parts.length >= 1 ? parts[parts.length - 1] : null;
 84			String secondToLast = parts.length >= 2 ? parts[parts.length -2] : null;
 85			if ("pgp".equals(lastPart) || "gpg".equals(lastPart)) {
 86				this.message.setEncryption(Message.ENCRYPTION_PGP);
 87			} else if (message.getEncryption() != Message.ENCRYPTION_OTR
 88					&& message.getEncryption() != Message.ENCRYPTION_AXOLOTL) {
 89				this.message.setEncryption(Message.ENCRYPTION_NONE);
 90			}
 91			String extension;
 92			if (VALID_CRYPTO_EXTENSIONS.contains(lastPart)) {
 93				extension = secondToLast;
 94			} else {
 95				extension = lastPart;
 96			}
 97			message.setRelativeFilePath(message.getUuid()+"."+extension);
 98			this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
 99			String reference = mUrl.getRef();
100			if (reference != null && reference.length() == 96) {
101				this.file.setKeyAndIv(CryptoHelper.hexToBytes(reference));
102			}
103
104			if ((this.message.getEncryption() == Message.ENCRYPTION_OTR
105					|| this.message.getEncryption() == Message.ENCRYPTION_AXOLOTL)
106					&& this.file.getKey() == null) {
107				this.message.setEncryption(Message.ENCRYPTION_NONE);
108					}
109			checkFileSize(interactive);
110		} catch (MalformedURLException e) {
111			this.cancel();
112		}
113	}
114
115	private void checkFileSize(boolean interactive) {
116		new Thread(new FileSizeChecker(interactive)).start();
117	}
118
119	@Override
120	public void cancel() {
121		this.canceled = true;
122		mHttpConnectionManager.finishConnection(this);
123		if (message.isFileOrImage()) {
124			message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
125		} else {
126			message.setTransferable(null);
127		}
128		mXmppConnectionService.updateConversationUi();
129	}
130
131	private void finish() {
132		mXmppConnectionService.getFileBackend().addImageFileToMedia(file);
133		message.setTransferable(null);
134		mHttpConnectionManager.finishConnection(this);
135		if (message.getEncryption() == Message.ENCRYPTION_PGP) {
136			message.getConversation().getAccount().getPgpDecryptionService().add(message);
137		}
138		mXmppConnectionService.updateConversationUi();
139		if (acceptedAutomatically) {
140			mXmppConnectionService.getNotificationService().push(message);
141		}
142	}
143
144	private void changeStatus(int status) {
145		this.mStatus = status;
146		mXmppConnectionService.updateConversationUi();
147	}
148
149	private void showToastForException(Exception e) {
150		e.printStackTrace();
151		if (e instanceof java.net.UnknownHostException) {
152			mXmppConnectionService.showErrorToastInUi(R.string.download_failed_server_not_found);
153		} else if (e instanceof java.net.ConnectException) {
154			mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_connect);
155		} else if (!(e instanceof  CancellationException)) {
156			mXmppConnectionService.showErrorToastInUi(R.string.download_failed_file_not_found);
157		}
158	}
159
160	private class FileSizeChecker implements Runnable {
161
162		private boolean interactive = false;
163
164		public FileSizeChecker(boolean interactive) {
165			this.interactive = interactive;
166		}
167
168		@Override
169		public void run() {
170			long size;
171			try {
172				size = retrieveFileSize();
173			} catch (SSLHandshakeException e) {
174				changeStatus(STATUS_OFFER_CHECK_FILESIZE);
175				HttpDownloadConnection.this.acceptedAutomatically = false;
176				HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
177				return;
178			} catch (IOException e) {
179				Log.d(Config.LOGTAG, "io exception in http file size checker: " + e.getMessage());
180				if (interactive) {
181					showToastForException(e);
182				}
183				cancel();
184				return;
185			}
186			file.setExpectedSize(size);
187			if (mHttpConnectionManager.hasStoragePermission() && size <= mHttpConnectionManager.getAutoAcceptFileSize()) {
188				HttpDownloadConnection.this.acceptedAutomatically = true;
189				new Thread(new FileDownloader(interactive)).start();
190			} else {
191				changeStatus(STATUS_OFFER);
192				HttpDownloadConnection.this.acceptedAutomatically = false;
193				HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
194			}
195		}
196
197		private long retrieveFileSize() throws IOException {
198			try {
199				Log.d(Config.LOGTAG, "retrieve file size. interactive:" + String.valueOf(interactive));
200				changeStatus(STATUS_CHECKING);
201				HttpURLConnection connection;
202				if (mUseTor) {
203					connection = (HttpURLConnection) mUrl.openConnection(mHttpConnectionManager.getProxy());
204				} else {
205					connection = (HttpURLConnection) mUrl.openConnection();
206				}
207				connection.setRequestMethod("HEAD");
208				Log.d(Config.LOGTAG,"url: "+connection.getURL().toString());
209				Log.d(Config.LOGTAG,"connection: "+connection.toString());
210				connection.setRequestProperty("User-Agent", mXmppConnectionService.getIqGenerator().getIdentityName());
211				if (connection instanceof HttpsURLConnection) {
212					mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
213				}
214				connection.connect();
215				String contentLength = connection.getHeaderField("Content-Length");
216				connection.disconnect();
217				if (contentLength == null) {
218					throw new IOException();
219				}
220				return Long.parseLong(contentLength, 10);
221			} catch (IOException e) {
222				throw e;
223			} catch (NumberFormatException e) {
224				throw new IOException();
225			}
226		}
227
228	}
229
230	private class FileDownloader implements Runnable {
231
232		private boolean interactive = false;
233
234		private OutputStream os;
235
236		public FileDownloader(boolean interactive) {
237			this.interactive = interactive;
238		}
239
240		@Override
241		public void run() {
242			try {
243				changeStatus(STATUS_DOWNLOADING);
244				download();
245				updateImageBounds();
246				finish();
247			} catch (SSLHandshakeException e) {
248				changeStatus(STATUS_OFFER);
249			} catch (Exception e) {
250				if (interactive) {
251					showToastForException(e);
252				}
253				cancel();
254			}
255		}
256
257		private void download()  throws Exception {
258			InputStream is = null;
259			PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_download_"+message.getUuid());
260			try {
261				wakeLock.acquire();
262				HttpURLConnection connection;
263				if (mUseTor) {
264					connection = (HttpURLConnection) mUrl.openConnection(mHttpConnectionManager.getProxy());
265				} else {
266					connection = (HttpURLConnection) mUrl.openConnection();
267				}
268				if (connection instanceof HttpsURLConnection) {
269					mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
270				}
271				connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getIdentityName());
272				final boolean tryResume = file.exists() && file.getKey() == null;
273				if (tryResume) {
274					Log.d(Config.LOGTAG,"http download trying resume");
275					long size = file.getSize();
276					connection.setRequestProperty("Range", "bytes="+size+"-");
277				}
278				connection.connect();
279				is = new BufferedInputStream(connection.getInputStream());
280				boolean serverResumed = "bytes".equals(connection.getHeaderField("Accept-Ranges"));
281				long transmitted = 0;
282				long expected = file.getExpectedSize();
283				if (tryResume && serverResumed) {
284					Log.d(Config.LOGTAG,"server resumed");
285					transmitted = file.getSize();
286					updateProgress((int) ((((double) transmitted) / expected) * 100));
287					os = AbstractConnectionManager.createAppendedOutputStream(file);
288				} else {
289					file.getParentFile().mkdirs();
290					file.createNewFile();
291					os = AbstractConnectionManager.createOutputStream(file, true);
292				}
293				int count = -1;
294				byte[] buffer = new byte[1024];
295				while ((count = is.read(buffer)) != -1) {
296					transmitted += count;
297					os.write(buffer, 0, count);
298					updateProgress((int) ((((double) transmitted) / expected) * 100));
299					if (canceled) {
300						throw new CancellationException();
301					}
302				}
303			} catch (CancellationException | IOException e) {
304				throw e;
305			} finally {
306				if (os != null) {
307					try {
308						os.flush();
309					} catch (final IOException ignored) {
310
311					}
312				}
313				FileBackend.close(os);
314				FileBackend.close(is);
315				wakeLock.release();
316			}
317		}
318
319		private void updateImageBounds() {
320			message.setType(Message.TYPE_FILE);
321			mXmppConnectionService.getFileBackend().updateFileParams(message, mUrl);
322			mXmppConnectionService.updateMessage(message);
323		}
324
325	}
326
327	public void updateProgress(int i) {
328		this.mProgress = i;
329		mXmppConnectionService.updateConversationUi();
330	}
331
332	@Override
333	public int getStatus() {
334		return this.mStatus;
335	}
336
337	@Override
338	public long getFileSize() {
339		if (this.file != null) {
340			return this.file.getExpectedSize();
341		} else {
342			return 0;
343		}
344	}
345
346	@Override
347	public int getProgress() {
348		return this.mProgress;
349	}
350}