HttpUploadConnection.java

  1package eu.siacs.conversations.http;
  2
  3import android.app.PendingIntent;
  4import android.content.Intent;
  5import android.net.Uri;
  6import android.util.Log;
  7import android.util.Pair;
  8
  9import java.io.IOException;
 10import java.io.InputStream;
 11import java.io.OutputStream;
 12import java.net.HttpURLConnection;
 13import java.net.MalformedURLException;
 14import java.net.URL;
 15
 16import javax.net.ssl.HttpsURLConnection;
 17
 18import eu.siacs.conversations.Config;
 19import eu.siacs.conversations.entities.Account;
 20import eu.siacs.conversations.entities.DownloadableFile;
 21import eu.siacs.conversations.entities.Message;
 22import eu.siacs.conversations.entities.Transferable;
 23import eu.siacs.conversations.persistance.FileBackend;
 24import eu.siacs.conversations.services.AbstractConnectionManager;
 25import eu.siacs.conversations.services.XmppConnectionService;
 26import eu.siacs.conversations.ui.UiCallback;
 27import eu.siacs.conversations.utils.CryptoHelper;
 28import eu.siacs.conversations.utils.Xmlns;
 29import eu.siacs.conversations.xml.Element;
 30import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 31import eu.siacs.conversations.xmpp.jid.Jid;
 32import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 33
 34public class HttpUploadConnection implements Transferable {
 35
 36	private HttpConnectionManager mHttpConnectionManager;
 37	private XmppConnectionService mXmppConnectionService;
 38
 39	private boolean canceled = false;
 40	private boolean delayed = false;
 41	private Account account;
 42	private DownloadableFile file;
 43	private Message message;
 44	private String mime;
 45	private URL mGetUrl;
 46	private URL mPutUrl;
 47
 48	private byte[] key = null;
 49
 50	private long transmitted = 0;
 51
 52	private InputStream mFileInputStream;
 53
 54	public HttpUploadConnection(HttpConnectionManager httpConnectionManager) {
 55		this.mHttpConnectionManager = httpConnectionManager;
 56		this.mXmppConnectionService = httpConnectionManager.getXmppConnectionService();
 57	}
 58
 59	@Override
 60	public boolean start() {
 61		return false;
 62	}
 63
 64	@Override
 65	public int getStatus() {
 66		return STATUS_UPLOADING;
 67	}
 68
 69	@Override
 70	public long getFileSize() {
 71		return this.file.getExpectedSize();
 72	}
 73
 74	@Override
 75	public int getProgress() {
 76		return (int) ((((double) transmitted) / file.getExpectedSize()) * 100);
 77	}
 78
 79	@Override
 80	public void cancel() {
 81		this.canceled = true;
 82	}
 83
 84	private void fail() {
 85		mHttpConnectionManager.finishUploadConnection(this);
 86		message.setTransferable(null);
 87		mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
 88		FileBackend.close(mFileInputStream);
 89	}
 90
 91	public void init(Message message, boolean delay) {
 92		this.message = message;
 93		message.setTransferable(this);
 94		mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
 95		this.account = message.getConversation().getAccount();
 96		this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
 97		this.mime = this.file.getMimeType();
 98		this.delayed = delay;
 99		if (Config.ENCRYPT_ON_HTTP_UPLOADED
100				|| message.getEncryption() == Message.ENCRYPTION_AXOLOTL
101				|| message.getEncryption() == Message.ENCRYPTION_OTR) {
102			this.key = new byte[48];
103			mXmppConnectionService.getRNG().nextBytes(this.key);
104			this.file.setKeyAndIv(this.key);
105		}
106		Pair<InputStream,Integer> pair = AbstractConnectionManager.createInputStream(file,true);
107		this.file.setExpectedSize(pair.second);
108		this.mFileInputStream = pair.first;
109		Jid host = account.getXmppConnection().findDiscoItemByFeature(Xmlns.HTTP_UPLOAD);
110		IqPacket request = mXmppConnectionService.getIqGenerator().requestHttpUploadSlot(host,file,mime);
111		mXmppConnectionService.sendIqPacket(account, request, new OnIqPacketReceived() {
112			@Override
113			public void onIqPacketReceived(Account account, IqPacket packet) {
114				if (packet.getType() == IqPacket.TYPE.RESULT) {
115					Element slot = packet.findChild("slot",Xmlns.HTTP_UPLOAD);
116					if (slot != null) {
117						try {
118							mGetUrl = new URL(slot.findChildContent("get"));
119							mPutUrl = new URL(slot.findChildContent("put"));
120							if (!canceled) {
121								new Thread(new FileUploader()).start();
122							}
123						} catch (MalformedURLException e) {
124							fail();
125						}
126					} else {
127						fail();
128					}
129				} else {
130					fail();
131				}
132			}
133		});
134	}
135
136	private class FileUploader implements Runnable {
137
138		@Override
139		public void run() {
140			this.upload();
141		}
142
143		private void upload() {
144			OutputStream os = null;
145			HttpURLConnection connection = null;
146			try {
147				Log.d(Config.LOGTAG, "uploading to " + mPutUrl.toString());
148				connection = (HttpURLConnection) mPutUrl.openConnection();
149				if (connection instanceof HttpsURLConnection) {
150					mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
151				}
152				connection.setRequestMethod("PUT");
153				connection.setFixedLengthStreamingMode((int) file.getExpectedSize());
154				connection.setRequestProperty("Content-Type", mime == null ? "application/octet-stream" : mime);
155				connection.setDoOutput(true);
156				connection.connect();
157				os = connection.getOutputStream();
158				transmitted = 0;
159				int count = -1;
160				byte[] buffer = new byte[4096];
161				while (((count = mFileInputStream.read(buffer)) != -1) && !canceled) {
162					transmitted += count;
163					os.write(buffer, 0, count);
164					mXmppConnectionService.updateConversationUi();
165				}
166				os.flush();
167				os.close();
168				mFileInputStream.close();
169				int code = connection.getResponseCode();
170				if (code == 200 || code == 201) {
171					Log.d(Config.LOGTAG, "finished uploading file");
172					if (key != null) {
173						mGetUrl = new URL(mGetUrl.toString() + "#" + CryptoHelper.bytesToHex(key));
174					}
175					mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl);
176					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
177					intent.setData(Uri.fromFile(file));
178					mXmppConnectionService.sendBroadcast(intent);
179					message.setTransferable(null);
180					message.setCounterpart(message.getConversation().getJid().toBareJid());
181					if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
182						mXmppConnectionService.getPgpEngine().encrypt(message, new UiCallback<Message>() {
183							@Override
184							public void success(Message message) {
185								mXmppConnectionService.resendMessage(message,delayed);
186							}
187
188							@Override
189							public void error(int errorCode, Message object) {
190								fail();
191							}
192
193							@Override
194							public void userInputRequried(PendingIntent pi, Message object) {
195								fail();
196							}
197						});
198					} else {
199						mXmppConnectionService.resendMessage(message, delayed);
200					}
201				} else {
202					fail();
203				}
204			} catch (IOException e) {
205				e.printStackTrace();
206				Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
207				fail();
208			} finally {
209				FileBackend.close(mFileInputStream);
210				FileBackend.close(os);
211				if (connection != null) {
212					connection.disconnect();
213				}
214			}
215		}
216	}
217}