HttpUploadConnection.java

  1package eu.siacs.conversations.http;
  2
  3import android.os.PowerManager;
  4import android.util.Log;
  5import android.util.Pair;
  6
  7import java.io.FileNotFoundException;
  8import java.io.IOException;
  9import java.io.InputStream;
 10import java.io.OutputStream;
 11import java.net.HttpURLConnection;
 12import java.net.MalformedURLException;
 13import java.net.URL;
 14
 15import javax.net.ssl.HttpsURLConnection;
 16
 17import eu.siacs.conversations.Config;
 18import eu.siacs.conversations.entities.Account;
 19import eu.siacs.conversations.entities.DownloadableFile;
 20import eu.siacs.conversations.entities.Message;
 21import eu.siacs.conversations.entities.Transferable;
 22import eu.siacs.conversations.parser.IqParser;
 23import eu.siacs.conversations.persistance.FileBackend;
 24import eu.siacs.conversations.services.AbstractConnectionManager;
 25import eu.siacs.conversations.services.XmppConnectionService;
 26import eu.siacs.conversations.utils.CryptoHelper;
 27import eu.siacs.conversations.xml.Namespace;
 28import eu.siacs.conversations.xml.Element;
 29import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 30import eu.siacs.conversations.xmpp.jid.Jid;
 31import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 32
 33public class HttpUploadConnection implements Transferable {
 34
 35	private HttpConnectionManager mHttpConnectionManager;
 36	private XmppConnectionService mXmppConnectionService;
 37
 38	private boolean canceled = false;
 39	private boolean delayed = false;
 40	private Account account;
 41	private DownloadableFile file;
 42	private Message message;
 43	private String mime;
 44	private URL mGetUrl;
 45	private URL mPutUrl;
 46	private boolean mUseTor = false;
 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		this.mUseTor = mXmppConnectionService.useTorToConnect();
 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 file == null ? 0 : file.getExpectedSize();
 73	}
 74
 75	@Override
 76	public int getProgress() {
 77		if (file == null) {
 78			return 0;
 79		}
 80		return (int) ((((double) transmitted) / file.getExpectedSize()) * 100);
 81	}
 82
 83	@Override
 84	public void cancel() {
 85		this.canceled = true;
 86	}
 87
 88	private void fail(String errorMessage) {
 89		mHttpConnectionManager.finishUploadConnection(this);
 90		message.setTransferable(null);
 91		mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, errorMessage);
 92		FileBackend.close(mFileInputStream);
 93	}
 94
 95	public void init(Message message, boolean delay) {
 96		this.message = message;
 97		this.account = message.getConversation().getAccount();
 98		this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
 99		if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
100			this.mime = "application/pgp-encrypted";
101		} else {
102			this.mime = this.file.getMimeType();
103		}
104		this.delayed = delay;
105		if (Config.ENCRYPT_ON_HTTP_UPLOADED
106				|| message.getEncryption() == Message.ENCRYPTION_AXOLOTL
107				|| message.getEncryption() == Message.ENCRYPTION_OTR) {
108			this.key = new byte[48];
109			mXmppConnectionService.getRNG().nextBytes(this.key);
110			this.file.setKeyAndIv(this.key);
111		}
112		Pair<InputStream,Integer> pair;
113		try {
114			pair = AbstractConnectionManager.createInputStream(file, true);
115		} catch (FileNotFoundException e) {
116			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not find file to upload - "+e.getMessage());
117			fail(e.getMessage());
118			return;
119		}
120		this.file.setExpectedSize(pair.second);
121		this.mFileInputStream = pair.first;
122		Jid host = account.getXmppConnection().findDiscoItemByFeature(Namespace.HTTP_UPLOAD);
123		IqPacket request = mXmppConnectionService.getIqGenerator().requestHttpUploadSlot(host,file,mime);
124		mXmppConnectionService.sendIqPacket(account, request, new OnIqPacketReceived() {
125			@Override
126			public void onIqPacketReceived(Account account, IqPacket packet) {
127				if (packet.getType() == IqPacket.TYPE.RESULT) {
128					Element slot = packet.findChild("slot", Namespace.HTTP_UPLOAD);
129					if (slot != null) {
130						try {
131							mGetUrl = new URL(slot.findChildContent("get"));
132							mPutUrl = new URL(slot.findChildContent("put"));
133							if (!canceled) {
134								new Thread(new FileUploader()).start();
135							}
136							return;
137						} catch (MalformedURLException e) {
138							//fall through
139						}
140					}
141				}
142				Log.d(Config.LOGTAG,account.getJid().toString()+": invalid response to slot request "+packet);
143				fail(IqParser.extractErrorMessage(packet));
144			}
145		});
146		message.setTransferable(this);
147		mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
148	}
149
150	private class FileUploader implements Runnable {
151
152		@Override
153		public void run() {
154			this.upload();
155		}
156
157		private void upload() {
158			OutputStream os = null;
159			HttpURLConnection connection = null;
160			PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_upload_"+message.getUuid());
161			try {
162				wakeLock.acquire();
163				Log.d(Config.LOGTAG, "uploading to " + mPutUrl.toString());
164				if (mUseTor) {
165					connection = (HttpURLConnection) mPutUrl.openConnection(mHttpConnectionManager.getProxy());
166				} else {
167					connection = (HttpURLConnection) mPutUrl.openConnection();
168				}
169				if (connection instanceof HttpsURLConnection) {
170					mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
171				}
172				connection.setRequestMethod("PUT");
173				connection.setFixedLengthStreamingMode((int) file.getExpectedSize());
174				connection.setRequestProperty("Content-Type", mime == null ? "application/octet-stream" : mime);
175				connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getIdentityName());
176				connection.setDoOutput(true);
177				connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
178				connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000);
179				connection.connect();
180				os = connection.getOutputStream();
181				transmitted = 0;
182				int count;
183				byte[] buffer = new byte[4096];
184				while (((count = mFileInputStream.read(buffer)) != -1) && !canceled) {
185					transmitted += count;
186					os.write(buffer, 0, count);
187					mHttpConnectionManager.updateConversationUi(false);
188				}
189				os.flush();
190				os.close();
191				mFileInputStream.close();
192				int code = connection.getResponseCode();
193				if (code == 200 || code == 201) {
194					Log.d(Config.LOGTAG, "finished uploading file");
195					if (key != null) {
196						mGetUrl = CryptoHelper.toAesGcmUrl(new URL(mGetUrl.toString() + "#" + CryptoHelper.bytesToHex(key)));
197					}
198					mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl);
199					mXmppConnectionService.getFileBackend().updateMediaScanner(file);
200					message.setTransferable(null);
201					message.setCounterpart(message.getConversation().getJid().toBareJid());
202					mXmppConnectionService.resendMessage(message, delayed);
203				} else {
204					Log.d(Config.LOGTAG,"http upload failed because response code was "+code);
205					fail("http upload failed because response code was "+code);
206				}
207			} catch (IOException e) {
208				e.printStackTrace();
209				Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
210				fail(e.getMessage());
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}