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