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