1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.annotation.TargetApi;
6import android.app.ActionBar;
7import android.app.Activity;
8import android.app.AlertDialog;
9import android.app.AlertDialog.Builder;
10import android.app.Dialog;
11import android.app.PendingIntent;
12import android.content.ActivityNotFoundException;
13import android.content.ClipData;
14import android.content.ClipboardManager;
15import android.content.ComponentName;
16import android.content.Context;
17import android.content.DialogInterface;
18import android.content.DialogInterface.OnClickListener;
19import android.content.Intent;
20import android.content.IntentSender.SendIntentException;
21import android.content.ServiceConnection;
22import android.content.SharedPreferences;
23import android.content.pm.PackageManager;
24import android.content.pm.ResolveInfo;
25import android.content.res.Resources;
26import android.content.res.TypedArray;
27import android.graphics.Bitmap;
28import android.graphics.Color;
29import android.graphics.Point;
30import android.graphics.drawable.BitmapDrawable;
31import android.graphics.drawable.Drawable;
32import android.net.ConnectivityManager;
33import android.net.Uri;
34import android.nfc.NdefMessage;
35import android.nfc.NdefRecord;
36import android.nfc.NfcAdapter;
37import android.nfc.NfcEvent;
38import android.os.AsyncTask;
39import android.os.Build;
40import android.os.Bundle;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.PowerManager;
44import android.os.SystemClock;
45import android.preference.PreferenceManager;
46import android.support.v4.content.ContextCompat;
47import android.text.InputType;
48import android.util.DisplayMetrics;
49import android.util.Pair;
50import android.view.MenuItem;
51import android.view.View;
52import android.view.inputmethod.InputMethodManager;
53import android.widget.EditText;
54import android.widget.ImageView;
55import android.widget.Toast;
56
57import net.java.otr4j.session.SessionID;
58
59import java.io.FileNotFoundException;
60import java.lang.ref.WeakReference;
61import java.util.ArrayList;
62import java.util.Collections;
63import java.util.List;
64import java.util.Map;
65import java.util.concurrent.RejectedExecutionException;
66import java.util.concurrent.atomic.AtomicInteger;
67
68import eu.siacs.conversations.Config;
69import eu.siacs.conversations.R;
70import eu.siacs.conversations.crypto.PgpEngine;
71import eu.siacs.conversations.entities.Account;
72import eu.siacs.conversations.entities.Contact;
73import eu.siacs.conversations.entities.Conversation;
74import eu.siacs.conversations.entities.Message;
75import eu.siacs.conversations.entities.MucOptions;
76import eu.siacs.conversations.entities.Presences;
77import eu.siacs.conversations.services.AvatarService;
78import eu.siacs.conversations.services.BarcodeProvider;
79import eu.siacs.conversations.services.XmppConnectionService;
80import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
81import eu.siacs.conversations.utils.CryptoHelper;
82import eu.siacs.conversations.utils.ExceptionHelper;
83import eu.siacs.conversations.utils.UIHelper;
84import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
85import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
86import eu.siacs.conversations.xmpp.jid.InvalidJidException;
87import eu.siacs.conversations.xmpp.jid.Jid;
88
89public abstract class XmppActivity extends Activity {
90
91 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
92 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
93 protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
94 protected static final int REQUEST_BATTERY_OP = 0x13849ff;
95
96 public static final String EXTRA_ACCOUNT = "account";
97
98 public XmppConnectionService xmppConnectionService;
99 public boolean xmppConnectionServiceBound = false;
100 protected boolean registeredListeners = false;
101
102 protected int mPrimaryTextColor;
103 protected int mSecondaryTextColor;
104 protected int mTertiaryTextColor;
105 protected int mPrimaryBackgroundColor;
106 protected int mSecondaryBackgroundColor;
107 protected int mColorRed;
108 protected int mColorOrange;
109 protected int mColorGreen;
110 protected int mPrimaryColor;
111
112 protected boolean mUseSubject = true;
113
114 private DisplayMetrics metrics;
115 protected int mTheme;
116 protected boolean mUsingEnterKey = false;
117
118 protected Toast mToast;
119
120 protected void hideToast() {
121 if (mToast != null) {
122 mToast.cancel();
123 }
124 }
125
126 protected void replaceToast(String msg) {
127 replaceToast(msg, true);
128 }
129
130 protected void replaceToast(String msg, boolean showlong) {
131 hideToast();
132 mToast = Toast.makeText(this, msg ,showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
133 mToast.show();
134 }
135
136 protected Runnable onOpenPGPKeyPublished = new Runnable() {
137 @Override
138 public void run() {
139 Toast.makeText(XmppActivity.this,R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
140 }
141 };
142
143 private long mLastUiRefresh = 0;
144 private Handler mRefreshUiHandler = new Handler();
145 private Runnable mRefreshUiRunnable = new Runnable() {
146 @Override
147 public void run() {
148 mLastUiRefresh = SystemClock.elapsedRealtime();
149 refreshUiReal();
150 }
151 };
152
153 protected ConferenceInvite mPendingConferenceInvite = null;
154
155
156 protected final void refreshUi() {
157 final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
158 if (diff > Config.REFRESH_UI_INTERVAL) {
159 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
160 runOnUiThread(mRefreshUiRunnable);
161 } else {
162 final long next = Config.REFRESH_UI_INTERVAL - diff;
163 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
164 mRefreshUiHandler.postDelayed(mRefreshUiRunnable,next);
165 }
166 }
167
168 abstract protected void refreshUiReal();
169
170 protected interface OnValueEdited {
171 String onValueEdited(String value);
172 }
173
174 public interface OnPresenceSelected {
175 void onPresenceSelected();
176 }
177
178 protected ServiceConnection mConnection = new ServiceConnection() {
179
180 @Override
181 public void onServiceConnected(ComponentName className, IBinder service) {
182 XmppConnectionBinder binder = (XmppConnectionBinder) service;
183 xmppConnectionService = binder.getService();
184 xmppConnectionServiceBound = true;
185 if (!registeredListeners && shouldRegisterListeners()) {
186 registerListeners();
187 registeredListeners = true;
188 }
189 onBackendConnected();
190 }
191
192 @Override
193 public void onServiceDisconnected(ComponentName arg0) {
194 xmppConnectionServiceBound = false;
195 }
196 };
197
198 @Override
199 protected void onStart() {
200 super.onStart();
201 if (!xmppConnectionServiceBound) {
202 connectToBackend();
203 } else {
204 if (!registeredListeners) {
205 this.registerListeners();
206 this.registeredListeners = true;
207 }
208 this.onBackendConnected();
209 }
210 }
211
212 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
213 protected boolean shouldRegisterListeners() {
214 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
215 return !isDestroyed() && !isFinishing();
216 } else {
217 return !isFinishing();
218 }
219 }
220
221 public void connectToBackend() {
222 Intent intent = new Intent(this, XmppConnectionService.class);
223 intent.setAction("ui");
224 startService(intent);
225 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
226 }
227
228 @Override
229 protected void onStop() {
230 super.onStop();
231 if (xmppConnectionServiceBound) {
232 if (registeredListeners) {
233 this.unregisterListeners();
234 this.registeredListeners = false;
235 }
236 unbindService(mConnection);
237 xmppConnectionServiceBound = false;
238 }
239 }
240
241 protected void hideKeyboard() {
242 InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
243
244 View focus = getCurrentFocus();
245
246 if (focus != null) {
247
248 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
249 InputMethodManager.HIDE_NOT_ALWAYS);
250 }
251 }
252
253 public boolean hasPgp() {
254 return xmppConnectionService.getPgpEngine() != null;
255 }
256
257 public void showInstallPgpDialog() {
258 Builder builder = new AlertDialog.Builder(this);
259 builder.setTitle(getString(R.string.openkeychain_required));
260 builder.setIconAttribute(android.R.attr.alertDialogIcon);
261 builder.setMessage(getText(R.string.openkeychain_required_long));
262 builder.setNegativeButton(getString(R.string.cancel), null);
263 builder.setNeutralButton(getString(R.string.restart),
264 new OnClickListener() {
265
266 @Override
267 public void onClick(DialogInterface dialog, int which) {
268 if (xmppConnectionServiceBound) {
269 unbindService(mConnection);
270 xmppConnectionServiceBound = false;
271 }
272 stopService(new Intent(XmppActivity.this,
273 XmppConnectionService.class));
274 finish();
275 }
276 });
277 builder.setPositiveButton(getString(R.string.install),
278 new OnClickListener() {
279
280 @Override
281 public void onClick(DialogInterface dialog, int which) {
282 Uri uri = Uri
283 .parse("market://details?id=org.sufficientlysecure.keychain");
284 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
285 uri);
286 PackageManager manager = getApplicationContext()
287 .getPackageManager();
288 List<ResolveInfo> infos = manager
289 .queryIntentActivities(marketIntent, 0);
290 if (infos.size() > 0) {
291 startActivity(marketIntent);
292 } else {
293 uri = Uri.parse("http://www.openkeychain.org/");
294 Intent browserIntent = new Intent(
295 Intent.ACTION_VIEW, uri);
296 startActivity(browserIntent);
297 }
298 finish();
299 }
300 });
301 builder.create().show();
302 }
303
304 abstract void onBackendConnected();
305
306 protected void registerListeners() {
307 if (this instanceof XmppConnectionService.OnConversationUpdate) {
308 this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
309 }
310 if (this instanceof XmppConnectionService.OnAccountUpdate) {
311 this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
312 }
313 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
314 this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
315 }
316 if (this instanceof XmppConnectionService.OnRosterUpdate) {
317 this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
318 }
319 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
320 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
321 }
322 if (this instanceof OnUpdateBlocklist) {
323 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
324 }
325 if (this instanceof XmppConnectionService.OnShowErrorToast) {
326 this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
327 }
328 if (this instanceof OnKeyStatusUpdated) {
329 this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
330 }
331 }
332
333 protected void unregisterListeners() {
334 if (this instanceof XmppConnectionService.OnConversationUpdate) {
335 this.xmppConnectionService.removeOnConversationListChangedListener();
336 }
337 if (this instanceof XmppConnectionService.OnAccountUpdate) {
338 this.xmppConnectionService.removeOnAccountListChangedListener();
339 }
340 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
341 this.xmppConnectionService.removeOnCaptchaRequestedListener();
342 }
343 if (this instanceof XmppConnectionService.OnRosterUpdate) {
344 this.xmppConnectionService.removeOnRosterUpdateListener();
345 }
346 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
347 this.xmppConnectionService.removeOnMucRosterUpdateListener();
348 }
349 if (this instanceof OnUpdateBlocklist) {
350 this.xmppConnectionService.removeOnUpdateBlocklistListener();
351 }
352 if (this instanceof XmppConnectionService.OnShowErrorToast) {
353 this.xmppConnectionService.removeOnShowErrorToastListener();
354 }
355 if (this instanceof OnKeyStatusUpdated) {
356 this.xmppConnectionService.removeOnNewKeysAvailableListener();
357 }
358 }
359
360 @Override
361 public boolean onOptionsItemSelected(final MenuItem item) {
362 switch (item.getItemId()) {
363 case R.id.action_settings:
364 startActivity(new Intent(this, SettingsActivity.class));
365 break;
366 case R.id.action_accounts:
367 startActivity(new Intent(this, ManageAccountActivity.class));
368 break;
369 case android.R.id.home:
370 finish();
371 break;
372 case R.id.action_show_qr_code:
373 showQrCode();
374 break;
375 }
376 return super.onOptionsItemSelected(item);
377 }
378
379 @Override
380 protected void onCreate(Bundle savedInstanceState) {
381 super.onCreate(savedInstanceState);
382 metrics = getResources().getDisplayMetrics();
383 ExceptionHelper.init(getApplicationContext());
384
385 mPrimaryTextColor = ContextCompat.getColor(this, R.color.black87);
386 mSecondaryTextColor = ContextCompat.getColor(this, R.color.black54);
387 mTertiaryTextColor = ContextCompat.getColor(this, R.color.black12);
388 mColorRed = ContextCompat.getColor(this, R.color.red800);
389 mColorOrange = ContextCompat.getColor(this, R.color.orange500);
390 mColorGreen = ContextCompat.getColor(this, R.color.green500);
391 mPrimaryColor = ContextCompat.getColor(this, R.color.primary500);
392 mPrimaryBackgroundColor = ContextCompat.getColor(this, R.color.grey50);
393 mSecondaryBackgroundColor = ContextCompat.getColor(this, R.color.grey200);
394
395 this.mTheme = findTheme();
396 if(isDarkTheme()) {
397 mPrimaryTextColor = ContextCompat.getColor(this, R.color.white);
398 mSecondaryTextColor = ContextCompat.getColor(this, R.color.white70);
399 mTertiaryTextColor = ContextCompat.getColor(this, R.color.white12);
400 mPrimaryBackgroundColor = ContextCompat.getColor(this, R.color.grey800);
401 mSecondaryBackgroundColor = ContextCompat.getColor(this, R.color.grey900);
402 }
403 setTheme(this.mTheme);
404
405 this.mUsingEnterKey = usingEnterKey();
406 mUseSubject = getPreferences().getBoolean("use_subject", getResources().getBoolean(R.bool.use_subject));
407 final ActionBar ab = getActionBar();
408 if (ab!=null) {
409 ab.setDisplayHomeAsUpEnabled(true);
410 }
411 }
412
413 public boolean isDarkTheme() {
414 return this.mTheme == R.style.ConversationsTheme_Dark || this.mTheme == R.style.ConversationsTheme_Dark_LargerText;
415 }
416
417 public int getThemeResource(int r_attr_name, int r_drawable_def) {
418 int[] attrs = { r_attr_name };
419 TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
420
421 int res = ta.getResourceId(0, r_drawable_def);
422 ta.recycle();
423
424 return res;
425 }
426
427 protected boolean isOptimizingBattery() {
428 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
429 PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
430 return !pm.isIgnoringBatteryOptimizations(getPackageName());
431 } else {
432 return false;
433 }
434 }
435
436 protected boolean isAffectedByDataSaver() {
437 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
438 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
439 return cm.isActiveNetworkMetered()
440 && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
441 } else {
442 return false;
443 }
444 }
445
446 protected boolean usingEnterKey() {
447 return getPreferences().getBoolean("display_enter_key", getResources().getBoolean(R.bool.display_enter_key));
448 }
449
450 protected SharedPreferences getPreferences() {
451 return PreferenceManager
452 .getDefaultSharedPreferences(getApplicationContext());
453 }
454
455 public boolean useSubjectToIdentifyConference() {
456 return mUseSubject;
457 }
458
459 public void switchToConversation(Conversation conversation) {
460 switchToConversation(conversation, null, false);
461 }
462
463 public void switchToConversation(Conversation conversation, String text,
464 boolean newTask) {
465 switchToConversation(conversation,text,null,false,newTask);
466 }
467
468 public void highlightInMuc(Conversation conversation, String nick) {
469 switchToConversation(conversation, null, nick, false, false);
470 }
471
472 public void privateMsgInMuc(Conversation conversation, String nick) {
473 switchToConversation(conversation, null, nick, true, false);
474 }
475
476 private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
477 Intent viewConversationIntent = new Intent(this,
478 ConversationActivity.class);
479 viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
480 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
481 conversation.getUuid());
482 if (text != null) {
483 viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
484 }
485 if (nick != null) {
486 viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
487 viewConversationIntent.putExtra(ConversationActivity.PRIVATE_MESSAGE,pm);
488 }
489 if (newTask) {
490 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
491 | Intent.FLAG_ACTIVITY_NEW_TASK
492 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
493 } else {
494 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
495 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
496 }
497 startActivity(viewConversationIntent);
498 finish();
499 }
500
501 public void switchToContactDetails(Contact contact) {
502 switchToContactDetails(contact, null);
503 }
504
505 public void switchToContactDetails(Contact contact, String messageFingerprint) {
506 Intent intent = new Intent(this, ContactDetailsActivity.class);
507 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
508 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().toBareJid().toString());
509 intent.putExtra("contact", contact.getJid().toString());
510 intent.putExtra("fingerprint", messageFingerprint);
511 startActivity(intent);
512 }
513
514 public void switchToAccount(Account account) {
515 switchToAccount(account, false);
516 }
517
518 public void switchToAccount(Account account, boolean init) {
519 Intent intent = new Intent(this, EditAccountActivity.class);
520 intent.putExtra("jid", account.getJid().toBareJid().toString());
521 intent.putExtra("init", init);
522 startActivity(intent);
523 }
524
525 protected void inviteToConversation(Conversation conversation) {
526 Intent intent = new Intent(getApplicationContext(),
527 ChooseContactActivity.class);
528 List<String> contacts = new ArrayList<>();
529 if (conversation.getMode() == Conversation.MODE_MULTI) {
530 for (MucOptions.User user : conversation.getMucOptions().getUsers(false)) {
531 Jid jid = user.getRealJid();
532 if (jid != null) {
533 contacts.add(jid.toBareJid().toString());
534 }
535 }
536 } else {
537 contacts.add(conversation.getJid().toBareJid().toString());
538 }
539 intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
540 intent.putExtra("conversation", conversation.getUuid());
541 intent.putExtra("multiple", true);
542 intent.putExtra("show_enter_jid", true);
543 intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
544 startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
545 }
546
547 protected void announcePgp(Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
548 if (account.getPgpId() == 0) {
549 choosePgpSignId(account);
550 } else {
551 String status = null;
552 if (manuallyChangePresence()) {
553 status = account.getPresenceStatusMessage();
554 }
555 if (status == null) {
556 status = "";
557 }
558 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<Account>() {
559
560 @Override
561 public void userInputRequried(PendingIntent pi, Account account) {
562 try {
563 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
564 } catch (final SendIntentException ignored) {
565 }
566 }
567
568 @Override
569 public void success(Account account) {
570 xmppConnectionService.databaseBackend.updateAccount(account);
571 xmppConnectionService.sendPresence(account);
572 if (conversation != null) {
573 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
574 xmppConnectionService.updateConversation(conversation);
575 refreshUi();
576 }
577 if (onSuccess != null) {
578 runOnUiThread(onSuccess);
579 }
580 }
581
582 @Override
583 public void error(int error, Account account) {
584 if (error == 0 && account != null) {
585 account.setPgpSignId(0);
586 account.unsetPgpSignature();
587 xmppConnectionService.databaseBackend.updateAccount(account);
588 choosePgpSignId(account);
589 } else {
590 displayErrorDialog(error);
591 }
592 }
593 });
594 }
595 }
596
597 protected boolean noAccountUsesPgp() {
598 if (!hasPgp()) {
599 return true;
600 }
601 for(Account account : xmppConnectionService.getAccounts()) {
602 if (account.getPgpId() != 0) {
603 return false;
604 }
605 }
606 return true;
607 }
608
609 @SuppressWarnings("deprecation")
610 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
611 protected void setListItemBackgroundOnView(View view) {
612 int sdk = android.os.Build.VERSION.SDK_INT;
613 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
614 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
615 } else {
616 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
617 }
618 }
619
620 protected void choosePgpSignId(Account account) {
621 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
622 @Override
623 public void success(Account account1) {
624 }
625
626 @Override
627 public void error(int errorCode, Account object) {
628
629 }
630
631 @Override
632 public void userInputRequried(PendingIntent pi, Account object) {
633 try {
634 startIntentSenderForResult(pi.getIntentSender(),
635 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
636 } catch (final SendIntentException ignored) {
637 }
638 }
639 });
640 }
641
642 protected void displayErrorDialog(final int errorCode) {
643 runOnUiThread(new Runnable() {
644
645 @Override
646 public void run() {
647 AlertDialog.Builder builder = new AlertDialog.Builder(
648 XmppActivity.this);
649 builder.setIconAttribute(android.R.attr.alertDialogIcon);
650 builder.setTitle(getString(R.string.error));
651 builder.setMessage(errorCode);
652 builder.setNeutralButton(R.string.accept, null);
653 builder.create().show();
654 }
655 });
656
657 }
658
659 protected void showAddToRosterDialog(final Conversation conversation) {
660 showAddToRosterDialog(conversation.getContact());
661 }
662
663 protected void showAddToRosterDialog(final Contact contact) {
664 AlertDialog.Builder builder = new AlertDialog.Builder(this);
665 builder.setTitle(contact.getJid().toString());
666 builder.setMessage(getString(R.string.not_in_roster));
667 builder.setNegativeButton(getString(R.string.cancel), null);
668 builder.setPositiveButton(getString(R.string.add_contact),
669 new DialogInterface.OnClickListener() {
670
671 @Override
672 public void onClick(DialogInterface dialog, int which) {
673 final Jid jid = contact.getJid();
674 Account account = contact.getAccount();
675 Contact contact = account.getRoster().getContact(jid);
676 xmppConnectionService.createContact(contact);
677 }
678 });
679 builder.create().show();
680 }
681
682 private void showAskForPresenceDialog(final Contact contact) {
683 AlertDialog.Builder builder = new AlertDialog.Builder(this);
684 builder.setTitle(contact.getJid().toString());
685 builder.setMessage(R.string.request_presence_updates);
686 builder.setNegativeButton(R.string.cancel, null);
687 builder.setPositiveButton(R.string.request_now,
688 new DialogInterface.OnClickListener() {
689
690 @Override
691 public void onClick(DialogInterface dialog, int which) {
692 if (xmppConnectionServiceBound) {
693 xmppConnectionService.sendPresencePacket(contact
694 .getAccount(), xmppConnectionService
695 .getPresenceGenerator()
696 .requestPresenceUpdatesFrom(contact));
697 }
698 }
699 });
700 builder.create().show();
701 }
702
703 private void warnMutalPresenceSubscription(final Conversation conversation,
704 final OnPresenceSelected listener) {
705 AlertDialog.Builder builder = new AlertDialog.Builder(this);
706 builder.setTitle(conversation.getContact().getJid().toString());
707 builder.setMessage(R.string.without_mutual_presence_updates);
708 builder.setNegativeButton(R.string.cancel, null);
709 builder.setPositiveButton(R.string.ignore, new OnClickListener() {
710
711 @Override
712 public void onClick(DialogInterface dialog, int which) {
713 conversation.setNextCounterpart(null);
714 if (listener != null) {
715 listener.onPresenceSelected();
716 }
717 }
718 });
719 builder.create().show();
720 }
721
722 protected void quickEdit(String previousValue, int hint, OnValueEdited callback) {
723 quickEdit(previousValue, callback, hint, false);
724 }
725
726 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
727 quickEdit(previousValue, callback, R.string.password, true);
728 }
729
730 @SuppressLint("InflateParams")
731 private void quickEdit(final String previousValue,
732 final OnValueEdited callback,
733 final int hint,
734 boolean password) {
735 AlertDialog.Builder builder = new AlertDialog.Builder(this);
736 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
737 final EditText editor = view.findViewById(R.id.editor);
738 if (password) {
739 editor.setInputType(InputType.TYPE_CLASS_TEXT
740 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
741 builder.setPositiveButton(R.string.accept,null);
742 } else {
743 builder.setPositiveButton(R.string.edit, null);
744 }
745 if (hint != 0) {
746 editor.setHint(hint);
747 }
748 editor.requestFocus();
749 editor.setText("");
750 if (previousValue != null) {
751 editor.getText().append(previousValue);
752 }
753 builder.setView(view);
754 builder.setNegativeButton(R.string.cancel, null);
755 final AlertDialog dialog = builder.create();
756 dialog.show();
757 View.OnClickListener clickListener = new View.OnClickListener() {
758
759 @Override
760 public void onClick(View v) {
761 String value = editor.getText().toString();
762 if (!value.equals(previousValue) && value.trim().length() > 0) {
763 String error = callback.onValueEdited(value);
764 if (error != null) {
765 editor.setError(error);
766 return;
767 }
768 }
769 dialog.dismiss();
770 }
771 };
772 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
773 }
774
775 public boolean hasStoragePermission(int requestCode) {
776 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
777 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
778 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
779 return false;
780 } else {
781 return true;
782 }
783 } else {
784 return true;
785 }
786 }
787
788 public void selectPresence(final Conversation conversation,
789 final OnPresenceSelected listener) {
790 final Contact contact = conversation.getContact();
791 if (conversation.hasValidOtrSession()) {
792 SessionID id = conversation.getOtrSession().getSessionID();
793 Jid jid;
794 try {
795 jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
796 } catch (InvalidJidException e) {
797 jid = null;
798 }
799 conversation.setNextCounterpart(jid);
800 listener.onPresenceSelected();
801 } else if (!contact.showInRoster()) {
802 showAddToRosterDialog(conversation);
803 } else {
804 final Presences presences = contact.getPresences();
805 if (presences.size() == 0) {
806 if (!contact.getOption(Contact.Options.TO)
807 && !contact.getOption(Contact.Options.ASKING)
808 && contact.getAccount().getStatus() == Account.State.ONLINE) {
809 showAskForPresenceDialog(contact);
810 } else if (!contact.getOption(Contact.Options.TO)
811 || !contact.getOption(Contact.Options.FROM)) {
812 warnMutalPresenceSubscription(conversation, listener);
813 } else {
814 conversation.setNextCounterpart(null);
815 listener.onPresenceSelected();
816 }
817 } else if (presences.size() == 1) {
818 String presence = presences.toResourceArray()[0];
819 try {
820 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
821 } catch (InvalidJidException e) {
822 conversation.setNextCounterpart(null);
823 }
824 listener.onPresenceSelected();
825 } else {
826 showPresenceSelectionDialog(presences,conversation,listener);
827 }
828 }
829 }
830
831 private void showPresenceSelectionDialog(Presences presences, final Conversation conversation, final OnPresenceSelected listener) {
832 final Contact contact = conversation.getContact();
833 AlertDialog.Builder builder = new AlertDialog.Builder(this);
834 builder.setTitle(getString(R.string.choose_presence));
835 final String[] resourceArray = presences.toResourceArray();
836 Pair<Map<String, String>, Map<String, String>> typeAndName = presences.toTypeAndNameMap();
837 final Map<String,String> resourceTypeMap = typeAndName.first;
838 final Map<String,String> resourceNameMap = typeAndName.second;
839 final String[] readableIdentities = new String[resourceArray.length];
840 final AtomicInteger selectedResource = new AtomicInteger(0);
841 for (int i = 0; i < resourceArray.length; ++i) {
842 String resource = resourceArray[i];
843 if (resource.equals(contact.getLastResource())) {
844 selectedResource.set(i);
845 }
846 String type = resourceTypeMap.get(resource);
847 String name = resourceNameMap.get(resource);
848 if (type != null) {
849 if (Collections.frequency(resourceTypeMap.values(),type) == 1) {
850 readableIdentities[i] = UIHelper.tranlasteType(this,type);
851 } else if (name != null) {
852 if (Collections.frequency(resourceNameMap.values(), name) == 1
853 || CryptoHelper.UUID_PATTERN.matcher(resource).matches()) {
854 readableIdentities[i] = UIHelper.tranlasteType(this,type) + " (" + name+")";
855 } else {
856 readableIdentities[i] = UIHelper.tranlasteType(this,type) + " (" + name +" / " + resource+")";
857 }
858 } else {
859 readableIdentities[i] = UIHelper.tranlasteType(this,type) + " (" + resource+")";
860 }
861 } else {
862 readableIdentities[i] = resource;
863 }
864 }
865 builder.setSingleChoiceItems(readableIdentities,
866 selectedResource.get(),
867 new DialogInterface.OnClickListener() {
868
869 @Override
870 public void onClick(DialogInterface dialog, int which) {
871 selectedResource.set(which);
872 }
873 });
874 builder.setNegativeButton(R.string.cancel, null);
875 builder.setPositiveButton(R.string.ok, new OnClickListener() {
876
877 @Override
878 public void onClick(DialogInterface dialog, int which) {
879 try {
880 Jid next = Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),resourceArray[selectedResource.get()]);
881 conversation.setNextCounterpart(next);
882 } catch (InvalidJidException e) {
883 conversation.setNextCounterpart(null);
884 }
885 listener.onPresenceSelected();
886 }
887 });
888 builder.create().show();
889 }
890
891 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
892 super.onActivityResult(requestCode, resultCode, data);
893 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
894 mPendingConferenceInvite = ConferenceInvite.parse(data);
895 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
896 if (mPendingConferenceInvite.execute(this)) {
897 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
898 mToast.show();
899 }
900 mPendingConferenceInvite = null;
901 }
902 }
903 }
904
905
906 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
907 @Override
908 public void success(final Conversation conversation) {
909 runOnUiThread(new Runnable() {
910 @Override
911 public void run() {
912 switchToConversation(conversation);
913 hideToast();
914 }
915 });
916 }
917
918 @Override
919 public void error(final int errorCode, Conversation object) {
920 runOnUiThread(new Runnable() {
921 @Override
922 public void run() {
923 replaceToast(getString(errorCode));
924 }
925 });
926 }
927
928 @Override
929 public void userInputRequried(PendingIntent pi, Conversation object) {
930
931 }
932 };
933
934 public int getTertiaryTextColor() {
935 return this.mTertiaryTextColor;
936 }
937
938 public int getSecondaryTextColor() {
939 return this.mSecondaryTextColor;
940 }
941
942 public int getPrimaryTextColor() {
943 return this.mPrimaryTextColor;
944 }
945
946 public int getWarningTextColor() {
947 return this.mColorRed;
948 }
949
950 public int getOnlineColor() {
951 return this.mColorGreen;
952 }
953
954 public int getPrimaryBackgroundColor() {
955 return this.mPrimaryBackgroundColor;
956 }
957
958 public int getSecondaryBackgroundColor() {
959 return this.mSecondaryBackgroundColor;
960 }
961
962 public int getPixel(int dp) {
963 DisplayMetrics metrics = getResources().getDisplayMetrics();
964 return ((int) (dp * metrics.density));
965 }
966
967 public boolean copyTextToClipboard(String text, int labelResId) {
968 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
969 String label = getResources().getString(labelResId);
970 if (mClipBoardManager != null) {
971 ClipData mClipData = ClipData.newPlainText(label, text);
972 mClipBoardManager.setPrimaryClip(mClipData);
973 return true;
974 }
975 return false;
976 }
977
978 protected void registerNdefPushMessageCallback() {
979 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
980 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
981 nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
982 @Override
983 public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
984 return new NdefMessage(new NdefRecord[]{
985 NdefRecord.createUri(getShareableUri()),
986 NdefRecord.createApplicationRecord("eu.siacs.conversations")
987 });
988 }
989 }, this);
990 }
991 }
992
993 protected boolean neverCompressPictures() {
994 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
995 }
996
997 protected boolean manuallyChangePresence() {
998 return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
999 }
1000
1001 protected void unregisterNdefPushMessageCallback() {
1002 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
1003 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
1004 nfcAdapter.setNdefPushMessageCallback(null,this);
1005 }
1006 }
1007
1008 protected String getShareableUri() {
1009 return getShareableUri(false);
1010 }
1011
1012 protected String getShareableUri(boolean http) {
1013 return null;
1014 }
1015
1016 protected void shareLink(boolean http) {
1017 String uri = getShareableUri(http);
1018 if (uri == null || uri.isEmpty()) {
1019 return;
1020 }
1021 Intent intent = new Intent(Intent.ACTION_SEND);
1022 intent.setType("text/plain");
1023 intent.putExtra(Intent.EXTRA_TEXT,getShareableUri(http));
1024 try {
1025 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
1026 } catch (ActivityNotFoundException e) {
1027 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
1028 }
1029 }
1030
1031 protected void launchOpenKeyChain(long keyId) {
1032 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
1033 try {
1034 startIntentSenderForResult(
1035 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
1036 0, 0);
1037 } catch (Throwable e) {
1038 Toast.makeText(XmppActivity.this,R.string.openpgp_error,Toast.LENGTH_SHORT).show();
1039 }
1040 }
1041
1042 @Override
1043 public void onResume() {
1044 super.onResume();
1045 if (this.getShareableUri() != null) {
1046 this.registerNdefPushMessageCallback();
1047 }
1048 }
1049
1050 protected int findTheme() {
1051 Boolean dark = getPreferences().getString(SettingsActivity.THEME, getResources().getString(R.string.theme)).equals("dark");
1052 Boolean larger = getPreferences().getBoolean("use_larger_font", getResources().getBoolean(R.bool.use_larger_font));
1053
1054 if(dark) {
1055 if(larger)
1056 return R.style.ConversationsTheme_Dark_LargerText;
1057 else
1058 return R.style.ConversationsTheme_Dark;
1059 } else {
1060 if (larger)
1061 return R.style.ConversationsTheme_LargerText;
1062 else
1063 return R.style.ConversationsTheme;
1064 }
1065 }
1066
1067 @Override
1068 public void onPause() {
1069 super.onPause();
1070 this.unregisterNdefPushMessageCallback();
1071 }
1072
1073 protected void showQrCode() {
1074 final String uri = getShareableUri();
1075 if (uri == null || uri.isEmpty()) {
1076 return;
1077 }
1078 Point size = new Point();
1079 getWindowManager().getDefaultDisplay().getSize(size);
1080 final int width = (size.x < size.y ? size.x : size.y);
1081 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
1082 ImageView view = new ImageView(this);
1083 view.setBackgroundColor(Color.WHITE);
1084 view.setImageBitmap(bitmap);
1085 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1086 builder.setView(view);
1087 builder.create().show();
1088 }
1089
1090 protected Account extractAccount(Intent intent) {
1091 String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1092 try {
1093 return jid != null ? xmppConnectionService.findAccountByJid(Jid.fromString(jid)) : null;
1094 } catch (InvalidJidException e) {
1095 return null;
1096 }
1097 }
1098
1099 public static class ConferenceInvite {
1100 private String uuid;
1101 private List<Jid> jids = new ArrayList<>();
1102
1103 public static ConferenceInvite parse(Intent data) {
1104 ConferenceInvite invite = new ConferenceInvite();
1105 invite.uuid = data.getStringExtra("conversation");
1106 if (invite.uuid == null) {
1107 return null;
1108 }
1109 try {
1110 if (data.getBooleanExtra("multiple", false)) {
1111 String[] toAdd = data.getStringArrayExtra("contacts");
1112 for (String item : toAdd) {
1113 invite.jids.add(Jid.fromString(item));
1114 }
1115 } else {
1116 invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
1117 }
1118 } catch (final InvalidJidException ignored) {
1119 return null;
1120 }
1121 return invite;
1122 }
1123
1124 public boolean execute(XmppActivity activity) {
1125 XmppConnectionService service = activity.xmppConnectionService;
1126 Conversation conversation = service.findConversationByUuid(this.uuid);
1127 if (conversation == null) {
1128 return false;
1129 }
1130 if (conversation.getMode() == Conversation.MODE_MULTI) {
1131 for (Jid jid : jids) {
1132 service.invite(conversation, jid);
1133 }
1134 return false;
1135 } else {
1136 jids.add(conversation.getJid().toBareJid());
1137 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1138 }
1139 }
1140 }
1141
1142 public AvatarService avatarService() {
1143 return xmppConnectionService.getAvatarService();
1144 }
1145
1146 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1147 private final WeakReference<ImageView> imageViewReference;
1148 private Message message = null;
1149
1150 public BitmapWorkerTask(ImageView imageView) {
1151 imageViewReference = new WeakReference<>(imageView);
1152 }
1153
1154 @Override
1155 protected Bitmap doInBackground(Message... params) {
1156 if (isCancelled()) {
1157 return null;
1158 }
1159 message = params[0];
1160 try {
1161 return xmppConnectionService.getFileBackend().getThumbnail(
1162 message, (int) (metrics.density * 288), false);
1163 } catch (FileNotFoundException e) {
1164 return null;
1165 }
1166 }
1167
1168 @Override
1169 protected void onPostExecute(Bitmap bitmap) {
1170 if (bitmap != null && !isCancelled()) {
1171 final ImageView imageView = imageViewReference.get();
1172 if (imageView != null) {
1173 imageView.setImageBitmap(bitmap);
1174 imageView.setBackgroundColor(0x00000000);
1175 }
1176 }
1177 }
1178 }
1179
1180 public void loadBitmap(Message message, ImageView imageView) {
1181 Bitmap bm;
1182 try {
1183 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1184 (int) (metrics.density * 288), true);
1185 } catch (FileNotFoundException e) {
1186 bm = null;
1187 }
1188 if (bm != null) {
1189 cancelPotentialWork(message, imageView);
1190 imageView.setImageBitmap(bm);
1191 imageView.setBackgroundColor(0x00000000);
1192 } else {
1193 if (cancelPotentialWork(message, imageView)) {
1194 imageView.setBackgroundColor(0xff333333);
1195 imageView.setImageDrawable(null);
1196 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1197 final AsyncDrawable asyncDrawable = new AsyncDrawable(
1198 getResources(), null, task);
1199 imageView.setImageDrawable(asyncDrawable);
1200 try {
1201 task.execute(message);
1202 } catch (final RejectedExecutionException ignored) {
1203 ignored.printStackTrace();
1204 }
1205 }
1206 }
1207 }
1208
1209 public static boolean cancelPotentialWork(Message message, ImageView imageView) {
1210 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1211
1212 if (bitmapWorkerTask != null) {
1213 final Message oldMessage = bitmapWorkerTask.message;
1214 if (oldMessage == null || message != oldMessage) {
1215 bitmapWorkerTask.cancel(true);
1216 } else {
1217 return false;
1218 }
1219 }
1220 return true;
1221 }
1222
1223 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1224 if (imageView != null) {
1225 final Drawable drawable = imageView.getDrawable();
1226 if (drawable instanceof AsyncDrawable) {
1227 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1228 return asyncDrawable.getBitmapWorkerTask();
1229 }
1230 }
1231 return null;
1232 }
1233
1234 static class AsyncDrawable extends BitmapDrawable {
1235 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1236
1237 public AsyncDrawable(Resources res, Bitmap bitmap,
1238 BitmapWorkerTask bitmapWorkerTask) {
1239 super(res, bitmap);
1240 bitmapWorkerTaskReference = new WeakReference<>(
1241 bitmapWorkerTask);
1242 }
1243
1244 public BitmapWorkerTask getBitmapWorkerTask() {
1245 return bitmapWorkerTaskReference.get();
1246 }
1247 }
1248}