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	}
 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			} else {
219				this.share.text = text;
220			}
221		} else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
222			this.share.image = type != null && type.startsWith("image/");
223			if (!this.share.image) {
224				return;
225			}
226			this.share.uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
227		}
228		if (xmppConnectionServiceBound) {
229			if (share.uuid != null) {
230				share();
231			} else {
232				xmppConnectionService.populateWithOrderedConversations(mConversations, this.share.uris.size() == 0);
233			}
234		}
235
236	}
237
238	protected boolean isImage(Uri uri) {
239		try {
240			String guess = URLConnection.guessContentTypeFromName(uri.toString());
241			return (guess != null && guess.startsWith("image/"));
242		} catch (final StringIndexOutOfBoundsException ignored) {
243			return false;
244		}
245	}
246
247	@Override
248	void onBackendConnected() {
249		if (xmppConnectionServiceBound && share != null
250				&& ((share.contact != null && share.account != null) || share.uuid != null)) {
251			share();
252			return;
253		}
254		refreshUiReal();
255	}
256
257	private void share() {
258		final Conversation conversation;
259		if (share.uuid != null) {
260			conversation = xmppConnectionService.findConversationByUuid(share.uuid);
261			if (conversation == null) {
262				return;
263			}
264		}else{
265			Account account;
266			try {
267				account = xmppConnectionService.findAccountByJid(Jid.fromString(share.account));
268			} catch (final InvalidJidException e) {
269				account = null;
270			}
271			if (account == null) {
272				return;
273			}
274
275			try {
276				conversation = xmppConnectionService
277						.findOrCreateConversation(account, Jid.fromString(share.contact), false,true);
278			} catch (final InvalidJidException e) {
279				return;
280			}
281		}
282		share(conversation);
283	}
284
285	private void share(final Conversation conversation) {
286		if (share.uris.size() != 0 && !hasStoragePermission(REQUEST_STORAGE_PERMISSION)) {
287			mPendingConversation = conversation;
288			return;
289		}
290		final Account account = conversation.getAccount();
291		final XmppConnection connection = account.getXmppConnection();
292		final long max = connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
293		mListView.setEnabled(false);
294		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP && !hasPgp()) {
295			if (share.uuid == null) {
296				showInstallPgpDialog();
297			} else {
298				Toast.makeText(this,R.string.openkeychain_not_installed,Toast.LENGTH_SHORT).show();
299				finish();
300			}
301			return;
302		}
303		if (share.uris.size() != 0) {
304			PresenceSelector.OnPresenceSelected callback = () -> {
305				attachmentCounter.set(share.uris.size());
306				if (share.image) {
307					share.multiple = share.uris.size() > 1;
308					replaceToast(getString(share.multiple ? R.string.preparing_images : R.string.preparing_image));
309					for (Iterator<Uri> i = share.uris.iterator(); i.hasNext(); i.remove()) {
310						final Uri uri = i.next();
311						delegateUriPermissionsToService(uri);
312						xmppConnectionService.attachImageToConversation(conversation, uri, attachFileCallback);
313					}
314				} else {
315					replaceToast(getString(R.string.preparing_file));
316					final Uri uri = share.uris.get(0);
317					delegateUriPermissionsToService(uri);
318					xmppConnectionService.attachFileToConversation(conversation, uri, attachFileCallback);
319				}
320			};
321			if (account.httpUploadAvailable()
322					&& ((share.image && !neverCompressPictures())
323					|| conversation.getMode() == Conversation.MODE_MULTI
324					|| FileBackend.allFilesUnderSize(this, share.uris, max))) {
325				callback.onPresenceSelected();
326			} else {
327				selectPresence(conversation, callback);
328			}
329		} else {
330			if (mReturnToPrevious && this.share.text != null && !this.share.text.isEmpty() ) {
331				final PresenceSelector.OnPresenceSelected callback = new PresenceSelector.OnPresenceSelected() {
332
333					private void finishAndSend(Message message) {
334						replaceToast(getString(R.string.shared_text_with_x, conversation.getName()));
335						finish();
336					}
337
338					private UiCallback<Message> messageEncryptionCallback = new UiCallback<Message>() {
339						@Override
340						public void success(final Message message) {
341							runOnUiThread(() -> finishAndSend(message));
342						}
343
344						@Override
345						public void error(final int errorCode, Message object) {
346							runOnUiThread(() -> {
347								replaceToast(getString(errorCode));
348								finish();
349							});
350						}
351
352						@Override
353						public void userInputRequried(PendingIntent pi, Message object) {
354							finish();
355						}
356					};
357
358					@Override
359					public void onPresenceSelected() {
360
361						final int encryption = conversation.getNextEncryption();
362
363						Message message = new Message(conversation,share.text, encryption);
364
365						Log.d(Config.LOGTAG,"on presence selected encrpytion="+encryption);
366
367						if (encryption == Message.ENCRYPTION_PGP) {
368							replaceToast(getString(R.string.encrypting_message));
369							xmppConnectionService.getPgpEngine().encrypt(message,messageEncryptionCallback);
370							return;
371						}
372						xmppConnectionService.sendMessage(message);
373						finishAndSend(message);
374					}
375				};
376				if (conversation.getNextEncryption() == Message.ENCRYPTION_OTR) {
377					selectPresence(conversation, callback);
378				} else {
379					callback.onPresenceSelected();
380				}
381			} else {
382				switchToConversation(conversation, this.share.text, true);
383			}
384		}
385
386	}
387
388	public void refreshUiReal() {
389		xmppConnectionService.populateWithOrderedConversations(mConversations, this.share != null && this.share.uris.size() == 0);
390		mAdapter.notifyDataSetChanged();
391	}
392
393	@Override
394	public void onBackPressed() {
395		if (attachmentCounter.get() >= 1) {
396			replaceToast(getString(R.string.sharing_files_please_wait));
397		} else {
398			super.onBackPressed();
399		}
400	}
401}