1package eu.siacs.conversations.ui;
2
3import android.app.PendingIntent;
4import android.content.Intent;
5import android.content.pm.PackageManager;
6import android.net.Uri;
7import android.os.Bundle;
8import android.util.Log;
9import android.view.Menu;
10import android.view.MenuItem;
11import android.view.View;
12import android.widget.AdapterView;
13import android.widget.AdapterView.OnItemClickListener;
14import android.widget.ListView;
15import android.widget.Toast;
16
17import java.net.URLConnection;
18import java.util.ArrayList;
19import java.util.Iterator;
20import java.util.List;
21import java.util.concurrent.atomic.AtomicInteger;
22
23import eu.siacs.conversations.Config;
24import eu.siacs.conversations.R;
25import eu.siacs.conversations.entities.Account;
26import eu.siacs.conversations.entities.Conversation;
27import eu.siacs.conversations.entities.Message;
28import eu.siacs.conversations.persistance.FileBackend;
29import eu.siacs.conversations.services.XmppConnectionService;
30import eu.siacs.conversations.ui.adapter.ConversationAdapter;
31import eu.siacs.conversations.xmpp.XmppConnection;
32import eu.siacs.conversations.xmpp.jid.InvalidJidException;
33import eu.siacs.conversations.xmpp.jid.Jid;
34
35public class ShareWithActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate {
36
37 private static final int REQUEST_STORAGE_PERMISSION = 0x733f32;
38 private boolean mReturnToPrevious = false;
39 private Conversation mPendingConversation = null;
40
41 @Override
42 public void onConversationUpdate() {
43 refreshUi();
44 }
45
46 private class Share {
47 public List<Uri> uris = new ArrayList<>();
48 public boolean image;
49 public String account;
50 public String contact;
51 public String text;
52 public String uuid;
53 public boolean multiple = false;
54 }
55
56 private Share share;
57
58 private static final int REQUEST_START_NEW_CONVERSATION = 0x0501;
59 private ListView mListView;
60 private ConversationAdapter mAdapter;
61 private List<Conversation> mConversations = new ArrayList<>();
62 private Toast mToast;
63 private AtomicInteger attachmentCounter = new AtomicInteger(0);
64
65 private UiInformableCallback<Message> attachFileCallback = new UiInformableCallback<Message>() {
66
67 @Override
68 public void inform(final String text) {
69 runOnUiThread(new Runnable() {
70 @Override
71 public void run() {
72 replaceToast(text);
73 }
74 });
75 }
76
77 @Override
78 public void userInputRequried(PendingIntent pi, Message object) {
79 // TODO Auto-generated method stub
80
81 }
82
83 @Override
84 public void success(final Message message) {
85 xmppConnectionService.sendMessage(message);
86 runOnUiThread(new Runnable() {
87 @Override
88 public void run() {
89 if (attachmentCounter.decrementAndGet() <=0 ) {
90 int resId;
91 if (share.image && share.multiple) {
92 resId = R.string.shared_images_with_x;
93 } else if (share.image) {
94 resId = R.string.shared_image_with_x;
95 } else {
96 resId = R.string.shared_file_with_x;
97 }
98 replaceToast(getString(resId, message.getConversation().getName()));
99 if (mReturnToPrevious) {
100 finish();
101 } else {
102 switchToConversation(message.getConversation());
103 }
104 }
105 }
106 });
107 }
108
109 @Override
110 public void error(final int errorCode, Message object) {
111 runOnUiThread(new Runnable() {
112 @Override
113 public void run() {
114 replaceToast(getString(errorCode));
115 if (attachmentCounter.decrementAndGet() <=0 ) {
116 finish();
117 }
118 }
119 });
120 }
121 };
122
123 protected void hideToast() {
124 if (mToast != null) {
125 mToast.cancel();
126 }
127 }
128
129 protected void replaceToast(String msg) {
130 hideToast();
131 mToast = Toast.makeText(this, msg ,Toast.LENGTH_LONG);
132 mToast.show();
133 }
134
135 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
136 super.onActivityResult(requestCode, resultCode, data);
137 if (requestCode == REQUEST_START_NEW_CONVERSATION
138 && resultCode == RESULT_OK) {
139 share.contact = data.getStringExtra("contact");
140 share.account = data.getStringExtra(EXTRA_ACCOUNT);
141 }
142 if (xmppConnectionServiceBound
143 && share != null
144 && share.contact != null
145 && share.account != null) {
146 share();
147 }
148 }
149
150 @Override
151 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
152 if (grantResults.length > 0)
153 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
154 if (requestCode == REQUEST_STORAGE_PERMISSION) {
155 if (this.mPendingConversation != null) {
156 share(this.mPendingConversation);
157 } else {
158 Log.d(Config.LOGTAG,"unable to find stored conversation");
159 }
160 }
161 } else {
162 Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
163 }
164 }
165
166 @Override
167 protected void onCreate(Bundle savedInstanceState) {
168 super.onCreate(savedInstanceState);
169
170 if (getActionBar() != null) {
171 getActionBar().setDisplayHomeAsUpEnabled(false);
172 getActionBar().setHomeButtonEnabled(false);
173 }
174
175 setContentView(R.layout.share_with);
176 setTitle(getString(R.string.title_activity_sharewith));
177
178 mListView = findViewById(R.id.choose_conversation_list);
179 mAdapter = new ConversationAdapter(this, this.mConversations);
180 mListView.setAdapter(mAdapter);
181 mListView.setOnItemClickListener(new OnItemClickListener() {
182
183 @Override
184 public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
185 share(mConversations.get(position));
186 }
187 });
188
189 this.share = new Share();
190 }
191
192 @Override
193 public boolean onCreateOptionsMenu(Menu menu) {
194 getMenuInflater().inflate(R.menu.share_with, menu);
195 return true;
196 }
197
198 @Override
199 public boolean onOptionsItemSelected(final MenuItem item) {
200 switch (item.getItemId()) {
201 case R.id.action_add:
202 final Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class);
203 startActivityForResult(intent, REQUEST_START_NEW_CONVERSATION);
204 return true;
205 }
206 return super.onOptionsItemSelected(item);
207 }
208
209 @Override
210 public void onStart() {
211 super.onStart();
212 Intent intent = getIntent();
213 if (intent == null) {
214 return;
215 }
216 this.mReturnToPrevious = getPreferences().getBoolean("return_to_previous", getResources().getBoolean(R.bool.return_to_previous));
217 final String type = intent.getType();
218 final String action = intent.getAction();
219 Log.d(Config.LOGTAG, "action: "+action+ ", type:"+type);
220 share.uuid = intent.getStringExtra("uuid");
221 if (Intent.ACTION_SEND.equals(action)) {
222 final String text = intent.getStringExtra(Intent.EXTRA_TEXT);
223 final Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
224 if (type != null && uri != null && (text == null || !type.equals("text/plain"))) {
225 this.share.uris.clear();
226 this.share.uris.add(uri);
227 this.share.image = type.startsWith("image/") || isImage(uri);
228 } else {
229 this.share.text = text;
230 }
231 } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
232 this.share.image = type != null && type.startsWith("image/");
233 if (!this.share.image) {
234 return;
235 }
236 this.share.uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
237 }
238 if (xmppConnectionServiceBound) {
239 if (share.uuid != null) {
240 share();
241 } else {
242 xmppConnectionService.populateWithOrderedConversations(mConversations, this.share.uris.size() == 0);
243 }
244 }
245
246 }
247
248 protected boolean isImage(Uri uri) {
249 try {
250 String guess = URLConnection.guessContentTypeFromName(uri.toString());
251 return (guess != null && guess.startsWith("image/"));
252 } catch (final StringIndexOutOfBoundsException ignored) {
253 return false;
254 }
255 }
256
257 @Override
258 void onBackendConnected() {
259 if (xmppConnectionServiceBound && share != null
260 && ((share.contact != null && share.account != null) || share.uuid != null)) {
261 share();
262 return;
263 }
264 refreshUiReal();
265 }
266
267 private void share() {
268 final Conversation conversation;
269 if (share.uuid != null) {
270 conversation = xmppConnectionService.findConversationByUuid(share.uuid);
271 if (conversation == null) {
272 return;
273 }
274 }else{
275 Account account;
276 try {
277 account = xmppConnectionService.findAccountByJid(Jid.fromString(share.account));
278 } catch (final InvalidJidException e) {
279 account = null;
280 }
281 if (account == null) {
282 return;
283 }
284
285 try {
286 conversation = xmppConnectionService
287 .findOrCreateConversation(account, Jid.fromString(share.contact), false,true);
288 } catch (final InvalidJidException e) {
289 return;
290 }
291 }
292 share(conversation);
293 }
294
295 private void share(final Conversation conversation) {
296 if (share.uris.size() != 0 && !hasStoragePermission(REQUEST_STORAGE_PERMISSION)) {
297 mPendingConversation = conversation;
298 return;
299 }
300 final Account account = conversation.getAccount();
301 final XmppConnection connection = account.getXmppConnection();
302 final long max = connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
303 mListView.setEnabled(false);
304 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP && !hasPgp()) {
305 if (share.uuid == null) {
306 showInstallPgpDialog();
307 } else {
308 Toast.makeText(this,R.string.openkeychain_not_installed,Toast.LENGTH_SHORT).show();
309 finish();
310 }
311 return;
312 }
313 if (share.uris.size() != 0) {
314 OnPresenceSelected callback = new OnPresenceSelected() {
315 @Override
316 public void onPresenceSelected() {
317 attachmentCounter.set(share.uris.size());
318 if (share.image) {
319 share.multiple = share.uris.size() > 1;
320 replaceToast(getString(share.multiple ? R.string.preparing_images : R.string.preparing_image));
321 for (Iterator<Uri> i = share.uris.iterator(); i.hasNext(); i.remove()) {
322 ShareWithActivity.this.xmppConnectionService
323 .attachImageToConversation(conversation, i.next(),
324 attachFileCallback);
325 }
326 } else {
327 replaceToast(getString(R.string.preparing_file));
328 ShareWithActivity.this.xmppConnectionService
329 .attachFileToConversation(conversation, share.uris.get(0), attachFileCallback);
330 }
331 }
332 };
333 if (account.httpUploadAvailable()
334 && ((share.image && !neverCompressPictures())
335 || conversation.getMode() == Conversation.MODE_MULTI
336 || FileBackend.allFilesUnderSize(this, share.uris, max))
337 && conversation.getNextEncryption() != Message.ENCRYPTION_OTR) {
338 callback.onPresenceSelected();
339 } else {
340 selectPresence(conversation, callback);
341 }
342 } else {
343 if (mReturnToPrevious && this.share.text != null && !this.share.text.isEmpty() ) {
344 final OnPresenceSelected callback = new OnPresenceSelected() {
345
346 private void finishAndSend(Message message) {
347 xmppConnectionService.sendMessage(message);
348 replaceToast(getString(R.string.shared_text_with_x, conversation.getName()));
349 finish();
350 }
351
352 private UiCallback<Message> messageEncryptionCallback = new UiCallback<Message>() {
353 @Override
354 public void success(final Message message) {
355 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
356 runOnUiThread(new Runnable() {
357 @Override
358 public void run() {
359 finishAndSend(message);
360 }
361 });
362 }
363
364 @Override
365 public void error(final int errorCode, Message object) {
366 runOnUiThread(new Runnable() {
367 @Override
368 public void run() {
369 replaceToast(getString(errorCode));
370 finish();
371 }
372 });
373 }
374
375 @Override
376 public void userInputRequried(PendingIntent pi, Message object) {
377 finish();
378 }
379 };
380
381 @Override
382 public void onPresenceSelected() {
383
384 final int encryption = conversation.getNextEncryption();
385
386 Message message = new Message(conversation,share.text, encryption);
387
388 Log.d(Config.LOGTAG,"on presence selected encrpytion="+encryption);
389
390 if (encryption == Message.ENCRYPTION_PGP) {
391 replaceToast(getString(R.string.encrypting_message));
392 xmppConnectionService.getPgpEngine().encrypt(message,messageEncryptionCallback);
393 return;
394 }
395
396 if (encryption == Message.ENCRYPTION_OTR) {
397 message.setCounterpart(conversation.getNextCounterpart());
398 }
399 finishAndSend(message);
400 }
401 };
402 if (conversation.getNextEncryption() == Message.ENCRYPTION_OTR) {
403 selectPresence(conversation, callback);
404 } else {
405 callback.onPresenceSelected();
406 }
407 } else {
408 switchToConversation(conversation, this.share.text, true);
409 }
410 }
411
412 }
413
414 public void refreshUiReal() {
415 xmppConnectionService.populateWithOrderedConversations(mConversations, this.share != null && this.share.uris.size() == 0);
416 mAdapter.notifyDataSetChanged();
417 }
418
419 @Override
420 public void onBackPressed() {
421 if (attachmentCounter.get() >= 1) {
422 replaceToast(getString(R.string.sharing_files_please_wait));
423 } else {
424 super.onBackPressed();
425 }
426 }
427}