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