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
161		setContentView(R.layout.activity_share_with);
162
163		setSupportActionBar(findViewById(R.id.toolbar));
164		if (getSupportActionBar() != null) {
165			getSupportActionBar().setDisplayHomeAsUpEnabled(false);
166			getSupportActionBar().setHomeButtonEnabled(false);
167		}
168
169		setTitle(getString(R.string.title_activity_sharewith));
170
171		mListView = findViewById(R.id.choose_conversation_list);
172		mAdapter = new ConversationAdapter(this, this.mConversations);
173		mListView.setAdapter(mAdapter);
174		mListView.setOnItemClickListener(new OnItemClickListener() {
175
176			@Override
177			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
178				share(mConversations.get(position));
179			}
180		});
181
182		this.share = new Share();
183	}
184
185	@Override
186	public boolean onCreateOptionsMenu(Menu menu) {
187		getMenuInflater().inflate(R.menu.share_with, menu);
188		return true;
189	}
190
191	@Override
192	public boolean onOptionsItemSelected(final MenuItem item) {
193		switch (item.getItemId()) {
194			case R.id.action_add:
195				final Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class);
196				startActivityForResult(intent, REQUEST_START_NEW_CONVERSATION);
197				return true;
198		}
199		return super.onOptionsItemSelected(item);
200	}
201
202	@Override
203	public void onStart() {
204		super.onStart();
205		Intent intent = getIntent();
206		if (intent == null) {
207			return;
208		}
209		this.mReturnToPrevious = getPreferences().getBoolean("return_to_previous", getResources().getBoolean(R.bool.return_to_previous));
210		final String type = intent.getType();
211		final String action = intent.getAction();
212		Log.d(Config.LOGTAG, "action: "+action+ ", type:"+type);
213		share.uuid = intent.getStringExtra("uuid");
214		if (Intent.ACTION_SEND.equals(action)) {
215			final String text = intent.getStringExtra(Intent.EXTRA_TEXT);
216			final Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
217			if (type != null && uri != null && (text == null || !type.equals("text/plain"))) {
218				this.share.uris.clear();
219				this.share.uris.add(uri);
220				this.share.image = type.startsWith("image/") || isImage(uri);
221				this.share.type = type;
222			} else {
223				this.share.text = text;
224			}
225		} else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
226			this.share.image = type != null && type.startsWith("image/");
227			if (!this.share.image) {
228				return;
229			}
230			this.share.uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
231		}
232		if (xmppConnectionServiceBound) {
233			if (share.uuid != null) {
234				share();
235			} else {
236				xmppConnectionService.populateWithOrderedConversations(mConversations, this.share.uris.size() == 0);
237			}
238		}
239
240	}
241
242	protected boolean isImage(Uri uri) {
243		try {
244			String guess = URLConnection.guessContentTypeFromName(uri.toString());
245			return (guess != null && guess.startsWith("image/"));
246		} catch (final StringIndexOutOfBoundsException ignored) {
247			return false;
248		}
249	}
250
251	@Override
252	void onBackendConnected() {
253		if (xmppConnectionServiceBound && share != null
254				&& ((share.contact != null && share.account != null) || share.uuid != null)) {
255			share();
256			return;
257		}
258		refreshUiReal();
259	}
260
261	private void share() {
262		final Conversation conversation;
263		if (share.uuid != null) {
264			conversation = xmppConnectionService.findConversationByUuid(share.uuid);
265			if (conversation == null) {
266				return;
267			}
268		}else{
269			Account account;
270			try {
271				account = xmppConnectionService.findAccountByJid(Jid.of(share.account));
272			} catch (final IllegalArgumentException e) {
273				account = null;
274			}
275			if (account == null) {
276				return;
277			}
278
279			try {
280				conversation = xmppConnectionService
281						.findOrCreateConversation(account, Jid.of(share.contact), false,true);
282			} catch (final IllegalArgumentException e) {
283				return;
284			}
285		}
286		share(conversation);
287	}
288
289	private void share(final Conversation conversation) {
290		if (share.uris.size() != 0 && !hasStoragePermission(REQUEST_STORAGE_PERMISSION)) {
291			mPendingConversation = conversation;
292			return;
293		}
294		final Account account = conversation.getAccount();
295		final XmppConnection connection = account.getXmppConnection();
296		final long max = connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
297		mListView.setEnabled(false);
298		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP && !hasPgp()) {
299			if (share.uuid == null) {
300				showInstallPgpDialog();
301			} else {
302				Toast.makeText(this,R.string.openkeychain_not_installed,Toast.LENGTH_SHORT).show();
303				finish();
304			}
305			return;
306		}
307		if (share.uris.size() != 0) {
308			PresenceSelector.OnPresenceSelected callback = () -> {
309				attachmentCounter.set(share.uris.size());
310				if (share.image) {
311					share.multiple = share.uris.size() > 1;
312					replaceToast(getString(share.multiple ? R.string.preparing_images : R.string.preparing_image));
313					for (Iterator<Uri> i = share.uris.iterator(); i.hasNext(); i.remove()) {
314						final Uri uri = i.next();
315						delegateUriPermissionsToService(uri);
316						xmppConnectionService.attachImageToConversation(conversation, uri, attachFileCallback);
317					}
318				} else {
319					replaceToast(getString(R.string.preparing_file));
320					final Uri uri = share.uris.get(0);
321					delegateUriPermissionsToService(uri);
322					xmppConnectionService.attachFileToConversation(conversation, uri, share.type,  attachFileCallback);
323				}
324			};
325			if (account.httpUploadAvailable()
326					&& ((share.image && !neverCompressPictures())
327					|| conversation.getMode() == Conversation.MODE_MULTI
328					|| FileBackend.allFilesUnderSize(this, share.uris, max))) {
329				callback.onPresenceSelected();
330			} else {
331				selectPresence(conversation, callback);
332			}
333		} else {
334			if (mReturnToPrevious && this.share.text != null && !this.share.text.isEmpty() ) {
335				final PresenceSelector.OnPresenceSelected callback = new PresenceSelector.OnPresenceSelected() {
336
337					private void finishAndSend(Message message) {
338						replaceToast(getString(R.string.shared_text_with_x, conversation.getName()));
339						finish();
340					}
341
342					private UiCallback<Message> messageEncryptionCallback = new UiCallback<Message>() {
343						@Override
344						public void success(final Message message) {
345							runOnUiThread(() -> finishAndSend(message));
346						}
347
348						@Override
349						public void error(final int errorCode, Message object) {
350							runOnUiThread(() -> {
351								replaceToast(getString(errorCode));
352								finish();
353							});
354						}
355
356						@Override
357						public void userInputRequried(PendingIntent pi, Message object) {
358							finish();
359						}
360					};
361
362					@Override
363					public void onPresenceSelected() {
364
365						final int encryption = conversation.getNextEncryption();
366
367						Message message = new Message(conversation,share.text, encryption);
368
369						Log.d(Config.LOGTAG,"on presence selected encrpytion="+encryption);
370
371						if (encryption == Message.ENCRYPTION_PGP) {
372							replaceToast(getString(R.string.encrypting_message));
373							xmppConnectionService.getPgpEngine().encrypt(message,messageEncryptionCallback);
374							return;
375						}
376						xmppConnectionService.sendMessage(message);
377						finishAndSend(message);
378					}
379				};
380				if (conversation.getNextEncryption() == Message.ENCRYPTION_OTR) {
381					selectPresence(conversation, callback);
382				} else {
383					callback.onPresenceSelected();
384				}
385			} else {
386				switchToConversation(conversation, this.share.text, true);
387			}
388		}
389
390	}
391
392	public void refreshUiReal() {
393		xmppConnectionService.populateWithOrderedConversations(mConversations, this.share != null && this.share.uris.size() == 0);
394		mAdapter.notifyDataSetChanged();
395	}
396
397	@Override
398	public void onBackPressed() {
399		if (attachmentCounter.get() >= 1) {
400			replaceToast(getString(R.string.sharing_files_please_wait));
401		} else {
402			super.onBackPressed();
403		}
404	}
405}