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