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