HttpDownloadConnection.java

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