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