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.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getIdentityName());
169 connection.setDoOutput(true);
170 connection.connect();
171 os = connection.getOutputStream();
172 transmitted = 0;
173 int count = -1;
174 byte[] buffer = new byte[4096];
175 while (((count = mFileInputStream.read(buffer)) != -1) && !canceled) {
176 transmitted += count;
177 os.write(buffer, 0, count);
178 mXmppConnectionService.updateConversationUi();
179 }
180 os.flush();
181 os.close();
182 mFileInputStream.close();
183 int code = connection.getResponseCode();
184 if (code == 200 || code == 201) {
185 Log.d(Config.LOGTAG, "finished uploading file");
186 if (key != null) {
187 mGetUrl = new URL(mGetUrl.toString() + "#" + CryptoHelper.bytesToHex(key));
188 }
189 mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl);
190 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
191 intent.setData(Uri.fromFile(file));
192 mXmppConnectionService.sendBroadcast(intent);
193 message.setTransferable(null);
194 message.setCounterpart(message.getConversation().getJid().toBareJid());
195 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
196 mXmppConnectionService.getPgpEngine().encrypt(message, new UiCallback<Message>() {
197 @Override
198 public void success(Message message) {
199 mXmppConnectionService.resendMessage(message,delayed);
200 }
201
202 @Override
203 public void error(int errorCode, Message object) {
204 fail();
205 }
206
207 @Override
208 public void userInputRequried(PendingIntent pi, Message object) {
209 fail();
210 }
211 });
212 } else {
213 mXmppConnectionService.resendMessage(message, delayed);
214 }
215 } else {
216 fail();
217 }
218 } catch (IOException e) {
219 e.printStackTrace();
220 Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
221 fail();
222 } finally {
223 FileBackend.close(mFileInputStream);
224 FileBackend.close(os);
225 if (connection != null) {
226 connection.disconnect();
227 }
228 wakeLock.release();
229 }
230 }
231 }
232}