1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.annotation.TargetApi;
6import android.app.PendingIntent;
7import android.content.ActivityNotFoundException;
8import android.content.ClipData;
9import android.content.ClipboardManager;
10import android.content.ComponentName;
11import android.content.Context;
12import android.content.ContextWrapper;
13import android.content.DialogInterface;
14import android.content.Intent;
15import android.content.IntentSender.SendIntentException;
16import android.content.ServiceConnection;
17import android.content.SharedPreferences;
18import android.content.pm.PackageManager;
19import android.content.pm.ResolveInfo;
20import android.content.res.Resources;
21import android.content.res.TypedArray;
22import android.graphics.Bitmap;
23import android.graphics.Color;
24import android.graphics.Point;
25import android.graphics.drawable.BitmapDrawable;
26import android.graphics.drawable.Drawable;
27import android.net.ConnectivityManager;
28import android.net.Uri;
29import android.os.AsyncTask;
30import android.os.Build;
31import android.os.Bundle;
32import android.os.Handler;
33import android.os.IBinder;
34import android.os.PowerManager;
35import android.os.SystemClock;
36import android.preference.PreferenceManager;
37import android.text.Html;
38import android.text.InputType;
39import android.util.DisplayMetrics;
40import android.util.Log;
41import android.view.Menu;
42import android.view.MenuItem;
43import android.view.View;
44import android.widget.ImageView;
45import android.widget.Toast;
46
47import androidx.annotation.BoolRes;
48import androidx.annotation.NonNull;
49import androidx.annotation.StringRes;
50import androidx.appcompat.app.AlertDialog;
51import androidx.appcompat.app.AlertDialog.Builder;
52import androidx.appcompat.app.AppCompatDelegate;
53import androidx.databinding.DataBindingUtil;
54
55import com.google.common.base.Strings;
56
57import java.io.IOException;
58import java.lang.ref.WeakReference;
59import java.util.ArrayList;
60import java.util.List;
61import java.util.concurrent.RejectedExecutionException;
62
63import eu.siacs.conversations.Config;
64import eu.siacs.conversations.R;
65import eu.siacs.conversations.crypto.PgpEngine;
66import eu.siacs.conversations.databinding.DialogQuickeditBinding;
67import eu.siacs.conversations.entities.Account;
68import eu.siacs.conversations.entities.Contact;
69import eu.siacs.conversations.entities.Conversation;
70import eu.siacs.conversations.entities.Message;
71import eu.siacs.conversations.entities.Presences;
72import eu.siacs.conversations.services.AvatarService;
73import eu.siacs.conversations.services.BarcodeProvider;
74import eu.siacs.conversations.services.QuickConversationsService;
75import eu.siacs.conversations.services.XmppConnectionService;
76import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
77import eu.siacs.conversations.ui.service.EmojiService;
78import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
79import eu.siacs.conversations.ui.util.PresenceSelector;
80import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
81import eu.siacs.conversations.utils.AccountUtils;
82import eu.siacs.conversations.utils.ExceptionHelper;
83import eu.siacs.conversations.utils.ThemeHelper;
84import eu.siacs.conversations.xmpp.Jid;
85import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
86import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
87
88public abstract class XmppActivity extends ActionBarActivity {
89
90 public static final String EXTRA_ACCOUNT = "account";
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 = 0x49ff;
95 public XmppConnectionService xmppConnectionService;
96 public boolean xmppConnectionServiceBound = false;
97
98 protected static final String FRAGMENT_TAG_DIALOG = "dialog";
99
100 private boolean isCameraFeatureAvailable = false;
101
102 protected int mTheme;
103 protected boolean mUsingEnterKey = false;
104 protected boolean mUseTor = false;
105 protected Toast mToast;
106 public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
107 protected ConferenceInvite mPendingConferenceInvite = null;
108 protected ServiceConnection mConnection = new ServiceConnection() {
109
110 @Override
111 public void onServiceConnected(ComponentName className, IBinder service) {
112 XmppConnectionBinder binder = (XmppConnectionBinder) service;
113 xmppConnectionService = binder.getService();
114 xmppConnectionServiceBound = true;
115 registerListeners();
116 onBackendConnected();
117 }
118
119 @Override
120 public void onServiceDisconnected(ComponentName arg0) {
121 xmppConnectionServiceBound = false;
122 }
123 };
124 private DisplayMetrics metrics;
125 private long mLastUiRefresh = 0;
126 private final Handler mRefreshUiHandler = new Handler();
127 private final Runnable mRefreshUiRunnable = () -> {
128 mLastUiRefresh = SystemClock.elapsedRealtime();
129 refreshUiReal();
130 };
131 private final UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
132 @Override
133 public void success(final Conversation conversation) {
134 runOnUiThread(() -> {
135 switchToConversation(conversation);
136 hideToast();
137 });
138 }
139
140 @Override
141 public void error(final int errorCode, Conversation object) {
142 runOnUiThread(() -> replaceToast(getString(errorCode)));
143 }
144
145 @Override
146 public void userInputRequired(PendingIntent pi, Conversation object) {
147
148 }
149 };
150 public boolean mSkipBackgroundBinding = false;
151
152 public static boolean cancelPotentialWork(Message message, ImageView imageView) {
153 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
154
155 if (bitmapWorkerTask != null) {
156 final Message oldMessage = bitmapWorkerTask.message;
157 if (oldMessage == null || message != oldMessage) {
158 bitmapWorkerTask.cancel(true);
159 } else {
160 return false;
161 }
162 }
163 return true;
164 }
165
166 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
167 if (imageView != null) {
168 final Drawable drawable = imageView.getDrawable();
169 if (drawable instanceof AsyncDrawable) {
170 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
171 return asyncDrawable.getBitmapWorkerTask();
172 }
173 }
174 return null;
175 }
176
177 protected void hideToast() {
178 if (mToast != null) {
179 mToast.cancel();
180 }
181 }
182
183 protected void replaceToast(String msg) {
184 replaceToast(msg, true);
185 }
186
187 protected void replaceToast(String msg, boolean showlong) {
188 hideToast();
189 mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
190 mToast.show();
191 }
192
193 protected final void refreshUi() {
194 final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
195 if (diff > Config.REFRESH_UI_INTERVAL) {
196 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
197 runOnUiThread(mRefreshUiRunnable);
198 } else {
199 final long next = Config.REFRESH_UI_INTERVAL - diff;
200 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
201 mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
202 }
203 }
204
205 abstract protected void refreshUiReal();
206
207 @Override
208 protected void onStart() {
209 super.onStart();
210 if (!xmppConnectionServiceBound) {
211 if (this.mSkipBackgroundBinding) {
212 Log.d(Config.LOGTAG, "skipping background binding");
213 } else {
214 connectToBackend();
215 }
216 } else {
217 this.registerListeners();
218 this.onBackendConnected();
219 }
220 this.mUsingEnterKey = usingEnterKey();
221 this.mUseTor = useTor();
222 }
223
224 public void connectToBackend() {
225 Intent intent = new Intent(this, XmppConnectionService.class);
226 intent.setAction("ui");
227 try {
228 startService(intent);
229 } catch (IllegalStateException e) {
230 Log.w(Config.LOGTAG, "unable to start service from " + getClass().getSimpleName());
231 }
232 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
233 }
234
235 @Override
236 protected void onStop() {
237 super.onStop();
238 if (xmppConnectionServiceBound) {
239 this.unregisterListeners();
240 unbindService(mConnection);
241 xmppConnectionServiceBound = false;
242 }
243 }
244
245
246 public boolean hasPgp() {
247 return xmppConnectionService.getPgpEngine() != null;
248 }
249
250 public void showInstallPgpDialog() {
251 Builder builder = new AlertDialog.Builder(this);
252 builder.setTitle(getString(R.string.openkeychain_required));
253 builder.setIconAttribute(android.R.attr.alertDialogIcon);
254 builder.setMessage(Html.fromHtml(getString(R.string.openkeychain_required_long, getString(R.string.app_name))));
255 builder.setNegativeButton(getString(R.string.cancel), null);
256 builder.setNeutralButton(getString(R.string.restart),
257 (dialog, which) -> {
258 if (xmppConnectionServiceBound) {
259 unbindService(mConnection);
260 xmppConnectionServiceBound = false;
261 }
262 stopService(new Intent(XmppActivity.this,
263 XmppConnectionService.class));
264 finish();
265 });
266 builder.setPositiveButton(getString(R.string.install),
267 (dialog, which) -> {
268 Uri uri = Uri
269 .parse("market://details?id=org.sufficientlysecure.keychain");
270 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
271 uri);
272 PackageManager manager = getApplicationContext()
273 .getPackageManager();
274 List<ResolveInfo> infos = manager
275 .queryIntentActivities(marketIntent, 0);
276 if (infos.size() > 0) {
277 startActivity(marketIntent);
278 } else {
279 uri = Uri.parse("http://www.openkeychain.org/");
280 Intent browserIntent = new Intent(
281 Intent.ACTION_VIEW, uri);
282 startActivity(browserIntent);
283 }
284 finish();
285 });
286 builder.create().show();
287 }
288
289 abstract void onBackendConnected();
290
291 protected void registerListeners() {
292 if (this instanceof XmppConnectionService.OnConversationUpdate) {
293 this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
294 }
295 if (this instanceof XmppConnectionService.OnAccountUpdate) {
296 this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
297 }
298 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
299 this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
300 }
301 if (this instanceof XmppConnectionService.OnRosterUpdate) {
302 this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
303 }
304 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
305 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
306 }
307 if (this instanceof OnUpdateBlocklist) {
308 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
309 }
310 if (this instanceof XmppConnectionService.OnShowErrorToast) {
311 this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
312 }
313 if (this instanceof OnKeyStatusUpdated) {
314 this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
315 }
316 if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
317 this.xmppConnectionService.setOnRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
318 }
319 }
320
321 protected void unregisterListeners() {
322 if (this instanceof XmppConnectionService.OnConversationUpdate) {
323 this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
324 }
325 if (this instanceof XmppConnectionService.OnAccountUpdate) {
326 this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
327 }
328 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
329 this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
330 }
331 if (this instanceof XmppConnectionService.OnRosterUpdate) {
332 this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
333 }
334 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
335 this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
336 }
337 if (this instanceof OnUpdateBlocklist) {
338 this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
339 }
340 if (this instanceof XmppConnectionService.OnShowErrorToast) {
341 this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
342 }
343 if (this instanceof OnKeyStatusUpdated) {
344 this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
345 }
346 if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
347 this.xmppConnectionService.removeRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
348 }
349 }
350
351 @Override
352 public boolean onOptionsItemSelected(final MenuItem item) {
353 switch (item.getItemId()) {
354 case R.id.action_settings:
355 startActivity(new Intent(this, SettingsActivity.class));
356 break;
357 case R.id.action_accounts:
358 AccountUtils.launchManageAccounts(this);
359 break;
360 case R.id.action_account:
361 AccountUtils.launchManageAccount(this);
362 break;
363 case android.R.id.home:
364 finish();
365 break;
366 case R.id.action_show_qr_code:
367 showQrCode();
368 break;
369 }
370 return super.onOptionsItemSelected(item);
371 }
372
373 public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
374 final Contact contact = conversation.getContact();
375 if (contact.showInRoster() || contact.isSelf()) {
376 final Presences presences = contact.getPresences();
377 if (presences.size() == 0) {
378 if (contact.isSelf()) {
379 conversation.setNextCounterpart(null);
380 listener.onPresenceSelected();
381 } else if (!contact.getOption(Contact.Options.TO)
382 && !contact.getOption(Contact.Options.ASKING)
383 && contact.getAccount().getStatus() == Account.State.ONLINE) {
384 showAskForPresenceDialog(contact);
385 } else if (!contact.getOption(Contact.Options.TO)
386 || !contact.getOption(Contact.Options.FROM)) {
387 PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
388 } else {
389 conversation.setNextCounterpart(null);
390 listener.onPresenceSelected();
391 }
392 } else if (presences.size() == 1) {
393 final String presence = presences.toResourceArray()[0];
394 conversation.setNextCounterpart(PresenceSelector.getNextCounterpart(contact, presence));
395 listener.onPresenceSelected();
396 } else {
397 PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
398 }
399 } else {
400 showAddToRosterDialog(conversation.getContact());
401 }
402 }
403
404 @SuppressLint("UnsupportedChromeOsCameraSystemFeature")
405 @Override
406 protected void onCreate(Bundle savedInstanceState) {
407 super.onCreate(savedInstanceState);
408 metrics = getResources().getDisplayMetrics();
409 ExceptionHelper.init(getApplicationContext());
410 new EmojiService(this).init();
411 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
412 this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
413 } else {
414 this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
415 }
416 this.mTheme = findTheme();
417 setTheme(this.mTheme);
418 }
419
420 protected boolean isCameraFeatureAvailable() {
421 return this.isCameraFeatureAvailable;
422 }
423
424 public boolean isDarkTheme() {
425 return ThemeHelper.isDark(mTheme);
426 }
427
428 public int getThemeResource(int r_attr_name, int r_drawable_def) {
429 int[] attrs = {r_attr_name};
430 TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
431
432 int res = ta.getResourceId(0, r_drawable_def);
433 ta.recycle();
434
435 return res;
436 }
437
438 protected boolean isOptimizingBattery() {
439 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
440 final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
441 return pm != null
442 && !pm.isIgnoringBatteryOptimizations(getPackageName());
443 } else {
444 return false;
445 }
446 }
447
448 protected boolean isAffectedByDataSaver() {
449 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
450 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
451 return cm != null
452 && cm.isActiveNetworkMetered()
453 && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
454 } else {
455 return false;
456 }
457 }
458
459 private boolean usingEnterKey() {
460 return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
461 }
462
463 private boolean useTor() {
464 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
465 }
466
467 protected SharedPreferences getPreferences() {
468 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
469 }
470
471 protected boolean getBooleanPreference(String name, @BoolRes int res) {
472 return getPreferences().getBoolean(name, getResources().getBoolean(res));
473 }
474
475 public void switchToConversation(Conversation conversation) {
476 switchToConversation(conversation, null);
477 }
478
479 public void switchToConversationAndQuote(Conversation conversation, String text) {
480 switchToConversation(conversation, text, true, null, false, false);
481 }
482
483 public void switchToConversation(Conversation conversation, String text) {
484 switchToConversation(conversation, text, false, null, false, false);
485 }
486
487 public void switchToConversationDoNotAppend(Conversation conversation, String text) {
488 switchToConversation(conversation, text, false, null, false, true);
489 }
490
491 public void highlightInMuc(Conversation conversation, String nick) {
492 switchToConversation(conversation, null, false, nick, false, false);
493 }
494
495 public void privateMsgInMuc(Conversation conversation, String nick) {
496 switchToConversation(conversation, null, false, nick, true, false);
497 }
498
499 private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
500 Intent intent = new Intent(this, ConversationsActivity.class);
501 intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
502 intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
503 if (text != null) {
504 intent.putExtra(Intent.EXTRA_TEXT, text);
505 if (asQuote) {
506 intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
507 }
508 }
509 if (nick != null) {
510 intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
511 intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
512 }
513 if (doNotAppend) {
514 intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
515 }
516 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
517 startActivity(intent);
518 finish();
519 }
520
521 public void switchToContactDetails(Contact contact) {
522 switchToContactDetails(contact, null);
523 }
524
525 public void switchToContactDetails(Contact contact, String messageFingerprint) {
526 Intent intent = new Intent(this, ContactDetailsActivity.class);
527 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
528 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
529 intent.putExtra("contact", contact.getJid().toEscapedString());
530 intent.putExtra("fingerprint", messageFingerprint);
531 startActivity(intent);
532 }
533
534 public void switchToAccount(Account account, String fingerprint) {
535 switchToAccount(account, false, fingerprint);
536 }
537
538 public void switchToAccount(Account account) {
539 switchToAccount(account, false, null);
540 }
541
542 public void switchToAccount(Account account, boolean init, String fingerprint) {
543 Intent intent = new Intent(this, EditAccountActivity.class);
544 intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
545 intent.putExtra("init", init);
546 if (init) {
547 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
548 }
549 if (fingerprint != null) {
550 intent.putExtra("fingerprint", fingerprint);
551 }
552 startActivity(intent);
553 if (init) {
554 overridePendingTransition(0, 0);
555 }
556 }
557
558 protected void delegateUriPermissionsToService(Uri uri) {
559 Intent intent = new Intent(this, XmppConnectionService.class);
560 intent.setAction(Intent.ACTION_SEND);
561 intent.setData(uri);
562 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
563 try {
564 startService(intent);
565 } catch (Exception e) {
566 Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
567 }
568 }
569
570 protected void inviteToConversation(Conversation conversation) {
571 startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
572 }
573
574 protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
575 if (account.getPgpId() == 0) {
576 choosePgpSignId(account);
577 } else {
578 final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
579 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
580
581 @Override
582 public void userInputRequired(PendingIntent pi, String signature) {
583 try {
584 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
585 } catch (final SendIntentException ignored) {
586 }
587 }
588
589 @Override
590 public void success(String signature) {
591 account.setPgpSignature(signature);
592 xmppConnectionService.databaseBackend.updateAccount(account);
593 xmppConnectionService.sendPresence(account);
594 if (conversation != null) {
595 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
596 xmppConnectionService.updateConversation(conversation);
597 refreshUi();
598 }
599 if (onSuccess != null) {
600 runOnUiThread(onSuccess);
601 }
602 }
603
604 @Override
605 public void error(int error, String signature) {
606 if (error == 0) {
607 account.setPgpSignId(0);
608 account.unsetPgpSignature();
609 xmppConnectionService.databaseBackend.updateAccount(account);
610 choosePgpSignId(account);
611 } else {
612 displayErrorDialog(error);
613 }
614 }
615 });
616 }
617 }
618
619 @SuppressWarnings("deprecation")
620 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
621 protected void setListItemBackgroundOnView(View view) {
622 int sdk = android.os.Build.VERSION.SDK_INT;
623 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
624 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
625 } else {
626 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
627 }
628 }
629
630 protected void choosePgpSignId(Account account) {
631 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
632 @Override
633 public void success(Account account1) {
634 }
635
636 @Override
637 public void error(int errorCode, Account object) {
638
639 }
640
641 @Override
642 public void userInputRequired(PendingIntent pi, Account object) {
643 try {
644 startIntentSenderForResult(pi.getIntentSender(),
645 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
646 } catch (final SendIntentException ignored) {
647 }
648 }
649 });
650 }
651
652 protected void displayErrorDialog(final int errorCode) {
653 runOnUiThread(() -> {
654 Builder builder = new Builder(XmppActivity.this);
655 builder.setIconAttribute(android.R.attr.alertDialogIcon);
656 builder.setTitle(getString(R.string.error));
657 builder.setMessage(errorCode);
658 builder.setNeutralButton(R.string.accept, null);
659 builder.create().show();
660 });
661
662 }
663
664 protected void showAddToRosterDialog(final Contact contact) {
665 AlertDialog.Builder builder = new AlertDialog.Builder(this);
666 builder.setTitle(contact.getJid().toString());
667 builder.setMessage(getString(R.string.not_in_roster));
668 builder.setNegativeButton(getString(R.string.cancel), null);
669 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact, true));
670 builder.create().show();
671 }
672
673 private void showAskForPresenceDialog(final Contact contact) {
674 AlertDialog.Builder builder = new AlertDialog.Builder(this);
675 builder.setTitle(contact.getJid().toString());
676 builder.setMessage(R.string.request_presence_updates);
677 builder.setNegativeButton(R.string.cancel, null);
678 builder.setPositiveButton(R.string.request_now,
679 (dialog, which) -> {
680 if (xmppConnectionServiceBound) {
681 xmppConnectionService.sendPresencePacket(contact
682 .getAccount(), xmppConnectionService
683 .getPresenceGenerator()
684 .requestPresenceUpdatesFrom(contact));
685 }
686 });
687 builder.create().show();
688 }
689
690 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
691 quickEdit(previousValue, callback, hint, false, false);
692 }
693
694 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
695 quickEdit(previousValue, callback, hint, false, permitEmpty);
696 }
697
698 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
699 quickEdit(previousValue, callback, R.string.password, true, false);
700 }
701
702 @SuppressLint("InflateParams")
703 private void quickEdit(final String previousValue,
704 final OnValueEdited callback,
705 final @StringRes int hint,
706 boolean password,
707 boolean permitEmpty) {
708 AlertDialog.Builder builder = new AlertDialog.Builder(this);
709 DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_quickedit, null, false);
710 if (password) {
711 binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
712 }
713 builder.setPositiveButton(R.string.accept, null);
714 if (hint != 0) {
715 binding.inputLayout.setHint(getString(hint));
716 }
717 binding.inputEditText.requestFocus();
718 if (previousValue != null) {
719 binding.inputEditText.getText().append(previousValue);
720 }
721 builder.setView(binding.getRoot());
722 builder.setNegativeButton(R.string.cancel, null);
723 final AlertDialog dialog = builder.create();
724 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
725 dialog.show();
726 View.OnClickListener clickListener = v -> {
727 String value = binding.inputEditText.getText().toString();
728 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
729 String error = callback.onValueEdited(value);
730 if (error != null) {
731 binding.inputLayout.setError(error);
732 return;
733 }
734 }
735 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
736 dialog.dismiss();
737 };
738 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
739 dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
740 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
741 dialog.dismiss();
742 }));
743 dialog.setCanceledOnTouchOutside(false);
744 dialog.setOnDismissListener(dialog1 -> {
745 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
746 });
747 }
748
749 protected boolean hasStoragePermission(int requestCode) {
750 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
751 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
752 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
753 return false;
754 } else {
755 return true;
756 }
757 } else {
758 return true;
759 }
760 }
761
762 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
763 super.onActivityResult(requestCode, resultCode, data);
764 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
765 mPendingConferenceInvite = ConferenceInvite.parse(data);
766 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
767 if (mPendingConferenceInvite.execute(this)) {
768 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
769 mToast.show();
770 }
771 mPendingConferenceInvite = null;
772 }
773 }
774 }
775
776 public boolean copyTextToClipboard(String text, int labelResId) {
777 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
778 String label = getResources().getString(labelResId);
779 if (mClipBoardManager != null) {
780 ClipData mClipData = ClipData.newPlainText(label, text);
781 mClipBoardManager.setPrimaryClip(mClipData);
782 return true;
783 }
784 return false;
785 }
786
787 protected boolean manuallyChangePresence() {
788 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
789 }
790
791 protected String getShareableUri() {
792 return getShareableUri(false);
793 }
794
795 protected String getShareableUri(boolean http) {
796 return null;
797 }
798
799 protected void shareLink(boolean http) {
800 String uri = getShareableUri(http);
801 if (uri == null || uri.isEmpty()) {
802 return;
803 }
804 Intent intent = new Intent(Intent.ACTION_SEND);
805 intent.setType("text/plain");
806 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
807 try {
808 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
809 } catch (ActivityNotFoundException e) {
810 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
811 }
812 }
813
814 protected void launchOpenKeyChain(long keyId) {
815 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
816 try {
817 startIntentSenderForResult(
818 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
819 0, 0);
820 } catch (Throwable e) {
821 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
822 }
823 }
824
825 @Override
826 public void onResume() {
827 super.onResume();
828 }
829
830 protected int findTheme() {
831 return ThemeHelper.find(this);
832 }
833
834 @Override
835 public void onPause() {
836 super.onPause();
837 }
838
839 @Override
840 public boolean onMenuOpened(int id, Menu menu) {
841 if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
842 MenuDoubleTabUtil.recordMenuOpen();
843 }
844 return super.onMenuOpened(id, menu);
845 }
846
847 protected void showQrCode() {
848 showQrCode(getShareableUri());
849 }
850
851 protected void showQrCode(final String uri) {
852 if (uri == null || uri.isEmpty()) {
853 return;
854 }
855 Point size = new Point();
856 getWindowManager().getDefaultDisplay().getSize(size);
857 final int width = (size.x < size.y ? size.x : size.y);
858 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
859 ImageView view = new ImageView(this);
860 view.setBackgroundColor(Color.WHITE);
861 view.setImageBitmap(bitmap);
862 AlertDialog.Builder builder = new AlertDialog.Builder(this);
863 builder.setView(view);
864 builder.create().show();
865 }
866
867 protected Account extractAccount(Intent intent) {
868 final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
869 try {
870 return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
871 } catch (IllegalArgumentException e) {
872 return null;
873 }
874 }
875
876 public AvatarService avatarService() {
877 return xmppConnectionService.getAvatarService();
878 }
879
880 public void loadBitmap(Message message, ImageView imageView) {
881 Bitmap bm;
882 try {
883 bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
884 } catch (IOException e) {
885 bm = null;
886 }
887 if (bm != null) {
888 cancelPotentialWork(message, imageView);
889 imageView.setImageBitmap(bm);
890 imageView.setBackgroundColor(0x00000000);
891 } else {
892 if (cancelPotentialWork(message, imageView)) {
893 imageView.setBackgroundColor(0xff333333);
894 imageView.setImageDrawable(null);
895 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
896 final AsyncDrawable asyncDrawable = new AsyncDrawable(
897 getResources(), null, task);
898 imageView.setImageDrawable(asyncDrawable);
899 try {
900 task.execute(message);
901 } catch (final RejectedExecutionException ignored) {
902 ignored.printStackTrace();
903 }
904 }
905 }
906 }
907
908 protected interface OnValueEdited {
909 String onValueEdited(String value);
910 }
911
912 public static class ConferenceInvite {
913 private String uuid;
914 private final List<Jid> jids = new ArrayList<>();
915
916 public static ConferenceInvite parse(Intent data) {
917 ConferenceInvite invite = new ConferenceInvite();
918 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
919 if (invite.uuid == null) {
920 return null;
921 }
922 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
923 return invite;
924 }
925
926 public boolean execute(XmppActivity activity) {
927 XmppConnectionService service = activity.xmppConnectionService;
928 Conversation conversation = service.findConversationByUuid(this.uuid);
929 if (conversation == null) {
930 return false;
931 }
932 if (conversation.getMode() == Conversation.MODE_MULTI) {
933 for (Jid jid : jids) {
934 service.invite(conversation, jid);
935 }
936 return false;
937 } else {
938 jids.add(conversation.getJid().asBareJid());
939 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
940 }
941 }
942 }
943
944 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
945 private final WeakReference<ImageView> imageViewReference;
946 private Message message = null;
947
948 private BitmapWorkerTask(ImageView imageView) {
949 this.imageViewReference = new WeakReference<>(imageView);
950 }
951
952 @Override
953 protected Bitmap doInBackground(Message... params) {
954 if (isCancelled()) {
955 return null;
956 }
957 message = params[0];
958 try {
959 final XmppActivity activity = find(imageViewReference);
960 if (activity != null && activity.xmppConnectionService != null) {
961 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
962 } else {
963 return null;
964 }
965 } catch (IOException e) {
966 return null;
967 }
968 }
969
970 @Override
971 protected void onPostExecute(final Bitmap bitmap) {
972 if (!isCancelled()) {
973 final ImageView imageView = imageViewReference.get();
974 if (imageView != null) {
975 imageView.setImageBitmap(bitmap);
976 imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
977 }
978 }
979 }
980 }
981
982 private static class AsyncDrawable extends BitmapDrawable {
983 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
984
985 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
986 super(res, bitmap);
987 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
988 }
989
990 private BitmapWorkerTask getBitmapWorkerTask() {
991 return bitmapWorkerTaskReference.get();
992 }
993 }
994
995 public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
996 final View view = viewWeakReference.get();
997 return view == null ? null : find(view);
998 }
999
1000 public static XmppActivity find(@NonNull final View view) {
1001 Context context = view.getContext();
1002 while (context instanceof ContextWrapper) {
1003 if (context instanceof XmppActivity) {
1004 return (XmppActivity) context;
1005 }
1006 context = ((ContextWrapper) context).getBaseContext();
1007 }
1008 return null;
1009 }
1010}