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