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