ShareWithActivity.java

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