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