HttpUploadConnection.java

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