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 this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
412 this.mTheme = findTheme();
413 setTheme(this.mTheme);
414 }
415
416 protected boolean isCameraFeatureAvailable() {
417 return this.isCameraFeatureAvailable;
418 }
419
420 public boolean isDarkTheme() {
421 return ThemeHelper.isDark(mTheme);
422 }
423
424 public int getThemeResource(int r_attr_name, int r_drawable_def) {
425 int[] attrs = {r_attr_name};
426 TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
427
428 int res = ta.getResourceId(0, r_drawable_def);
429 ta.recycle();
430
431 return res;
432 }
433
434 protected boolean isOptimizingBattery() {
435 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
436 final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
437 return pm != null
438 && !pm.isIgnoringBatteryOptimizations(getPackageName());
439 } else {
440 return false;
441 }
442 }
443
444 protected boolean isAffectedByDataSaver() {
445 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
446 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
447 return cm != null
448 && cm.isActiveNetworkMetered()
449 && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
450 } else {
451 return false;
452 }
453 }
454
455 private boolean usingEnterKey() {
456 return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
457 }
458
459 private boolean useTor() {
460 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
461 }
462
463 protected SharedPreferences getPreferences() {
464 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
465 }
466
467 protected boolean getBooleanPreference(String name, @BoolRes int res) {
468 return getPreferences().getBoolean(name, getResources().getBoolean(res));
469 }
470
471 public void switchToConversation(Conversation conversation) {
472 switchToConversation(conversation, null);
473 }
474
475 public void switchToConversationAndQuote(Conversation conversation, String text) {
476 switchToConversation(conversation, text, true, null, false, false);
477 }
478
479 public void switchToConversation(Conversation conversation, String text) {
480 switchToConversation(conversation, text, false, null, false, false);
481 }
482
483 public void switchToConversationDoNotAppend(Conversation conversation, String text) {
484 switchToConversation(conversation, text, false, null, false, true);
485 }
486
487 public void highlightInMuc(Conversation conversation, String nick) {
488 switchToConversation(conversation, null, false, nick, false, false);
489 }
490
491 public void privateMsgInMuc(Conversation conversation, String nick) {
492 switchToConversation(conversation, null, false, nick, true, false);
493 }
494
495 private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
496 Intent intent = new Intent(this, ConversationsActivity.class);
497 intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
498 intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
499 if (text != null) {
500 intent.putExtra(Intent.EXTRA_TEXT, text);
501 if (asQuote) {
502 intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
503 }
504 }
505 if (nick != null) {
506 intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
507 intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
508 }
509 if (doNotAppend) {
510 intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
511 }
512 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
513 startActivity(intent);
514 finish();
515 }
516
517 public void switchToContactDetails(Contact contact) {
518 switchToContactDetails(contact, null);
519 }
520
521 public void switchToContactDetails(Contact contact, String messageFingerprint) {
522 Intent intent = new Intent(this, ContactDetailsActivity.class);
523 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
524 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
525 intent.putExtra("contact", contact.getJid().toEscapedString());
526 intent.putExtra("fingerprint", messageFingerprint);
527 startActivity(intent);
528 }
529
530 public void switchToAccount(Account account, String fingerprint) {
531 switchToAccount(account, false, fingerprint);
532 }
533
534 public void switchToAccount(Account account) {
535 switchToAccount(account, false, null);
536 }
537
538 public void switchToAccount(Account account, boolean init, String fingerprint) {
539 Intent intent = new Intent(this, EditAccountActivity.class);
540 intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
541 intent.putExtra("init", init);
542 if (init) {
543 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
544 }
545 if (fingerprint != null) {
546 intent.putExtra("fingerprint", fingerprint);
547 }
548 startActivity(intent);
549 if (init) {
550 overridePendingTransition(0, 0);
551 }
552 }
553
554 protected void delegateUriPermissionsToService(Uri uri) {
555 Intent intent = new Intent(this, XmppConnectionService.class);
556 intent.setAction(Intent.ACTION_SEND);
557 intent.setData(uri);
558 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
559 try {
560 startService(intent);
561 } catch (Exception e) {
562 Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
563 }
564 }
565
566 protected void inviteToConversation(Conversation conversation) {
567 startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
568 }
569
570 protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
571 if (account.getPgpId() == 0) {
572 choosePgpSignId(account);
573 } else {
574 final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
575 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
576
577 @Override
578 public void userInputRequired(PendingIntent pi, String signature) {
579 try {
580 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
581 } catch (final SendIntentException ignored) {
582 }
583 }
584
585 @Override
586 public void success(String signature) {
587 account.setPgpSignature(signature);
588 xmppConnectionService.databaseBackend.updateAccount(account);
589 xmppConnectionService.sendPresence(account);
590 if (conversation != null) {
591 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
592 xmppConnectionService.updateConversation(conversation);
593 refreshUi();
594 }
595 if (onSuccess != null) {
596 runOnUiThread(onSuccess);
597 }
598 }
599
600 @Override
601 public void error(int error, String signature) {
602 if (error == 0) {
603 account.setPgpSignId(0);
604 account.unsetPgpSignature();
605 xmppConnectionService.databaseBackend.updateAccount(account);
606 choosePgpSignId(account);
607 } else {
608 displayErrorDialog(error);
609 }
610 }
611 });
612 }
613 }
614
615 @SuppressWarnings("deprecation")
616 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
617 protected void setListItemBackgroundOnView(View view) {
618 int sdk = android.os.Build.VERSION.SDK_INT;
619 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
620 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
621 } else {
622 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
623 }
624 }
625
626 protected void choosePgpSignId(Account account) {
627 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
628 @Override
629 public void success(Account account1) {
630 }
631
632 @Override
633 public void error(int errorCode, Account object) {
634
635 }
636
637 @Override
638 public void userInputRequired(PendingIntent pi, Account object) {
639 try {
640 startIntentSenderForResult(pi.getIntentSender(),
641 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
642 } catch (final SendIntentException ignored) {
643 }
644 }
645 });
646 }
647
648 protected void displayErrorDialog(final int errorCode) {
649 runOnUiThread(() -> {
650 Builder builder = new Builder(XmppActivity.this);
651 builder.setIconAttribute(android.R.attr.alertDialogIcon);
652 builder.setTitle(getString(R.string.error));
653 builder.setMessage(errorCode);
654 builder.setNeutralButton(R.string.accept, null);
655 builder.create().show();
656 });
657
658 }
659
660 protected void showAddToRosterDialog(final Contact contact) {
661 AlertDialog.Builder builder = new AlertDialog.Builder(this);
662 builder.setTitle(contact.getJid().toString());
663 builder.setMessage(getString(R.string.not_in_roster));
664 builder.setNegativeButton(getString(R.string.cancel), null);
665 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact, true));
666 builder.create().show();
667 }
668
669 private void showAskForPresenceDialog(final Contact contact) {
670 AlertDialog.Builder builder = new AlertDialog.Builder(this);
671 builder.setTitle(contact.getJid().toString());
672 builder.setMessage(R.string.request_presence_updates);
673 builder.setNegativeButton(R.string.cancel, null);
674 builder.setPositiveButton(R.string.request_now,
675 (dialog, which) -> {
676 if (xmppConnectionServiceBound) {
677 xmppConnectionService.sendPresencePacket(contact
678 .getAccount(), xmppConnectionService
679 .getPresenceGenerator()
680 .requestPresenceUpdatesFrom(contact));
681 }
682 });
683 builder.create().show();
684 }
685
686 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
687 quickEdit(previousValue, callback, hint, false, false);
688 }
689
690 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
691 quickEdit(previousValue, callback, hint, false, permitEmpty);
692 }
693
694 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
695 quickEdit(previousValue, callback, R.string.password, true, false);
696 }
697
698 @SuppressLint("InflateParams")
699 private void quickEdit(final String previousValue,
700 final OnValueEdited callback,
701 final @StringRes int hint,
702 boolean password,
703 boolean permitEmpty) {
704 AlertDialog.Builder builder = new AlertDialog.Builder(this);
705 DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_quickedit, null, false);
706 if (password) {
707 binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
708 }
709 builder.setPositiveButton(R.string.accept, null);
710 if (hint != 0) {
711 binding.inputLayout.setHint(getString(hint));
712 }
713 binding.inputEditText.requestFocus();
714 if (previousValue != null) {
715 binding.inputEditText.getText().append(previousValue);
716 }
717 builder.setView(binding.getRoot());
718 builder.setNegativeButton(R.string.cancel, null);
719 final AlertDialog dialog = builder.create();
720 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
721 dialog.show();
722 View.OnClickListener clickListener = v -> {
723 String value = binding.inputEditText.getText().toString();
724 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
725 String error = callback.onValueEdited(value);
726 if (error != null) {
727 binding.inputLayout.setError(error);
728 return;
729 }
730 }
731 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
732 dialog.dismiss();
733 };
734 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
735 dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
736 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
737 dialog.dismiss();
738 }));
739 dialog.setCanceledOnTouchOutside(false);
740 dialog.setOnDismissListener(dialog1 -> {
741 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
742 });
743 }
744
745 protected boolean hasStoragePermission(int requestCode) {
746 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
747 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
748 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
749 return false;
750 } else {
751 return true;
752 }
753 } else {
754 return true;
755 }
756 }
757
758 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
759 super.onActivityResult(requestCode, resultCode, data);
760 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
761 mPendingConferenceInvite = ConferenceInvite.parse(data);
762 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
763 if (mPendingConferenceInvite.execute(this)) {
764 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
765 mToast.show();
766 }
767 mPendingConferenceInvite = null;
768 }
769 }
770 }
771
772 public boolean copyTextToClipboard(String text, int labelResId) {
773 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
774 String label = getResources().getString(labelResId);
775 if (mClipBoardManager != null) {
776 ClipData mClipData = ClipData.newPlainText(label, text);
777 mClipBoardManager.setPrimaryClip(mClipData);
778 return true;
779 }
780 return false;
781 }
782
783 protected boolean manuallyChangePresence() {
784 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
785 }
786
787 protected String getShareableUri() {
788 return getShareableUri(false);
789 }
790
791 protected String getShareableUri(boolean http) {
792 return null;
793 }
794
795 protected void shareLink(boolean http) {
796 String uri = getShareableUri(http);
797 if (uri == null || uri.isEmpty()) {
798 return;
799 }
800 Intent intent = new Intent(Intent.ACTION_SEND);
801 intent.setType("text/plain");
802 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
803 try {
804 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
805 } catch (ActivityNotFoundException e) {
806 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
807 }
808 }
809
810 protected void launchOpenKeyChain(long keyId) {
811 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
812 try {
813 startIntentSenderForResult(
814 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
815 0, 0);
816 } catch (Throwable e) {
817 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
818 }
819 }
820
821 @Override
822 public void onResume() {
823 super.onResume();
824 }
825
826 protected int findTheme() {
827 return ThemeHelper.find(this);
828 }
829
830 @Override
831 public void onPause() {
832 super.onPause();
833 }
834
835 @Override
836 public boolean onMenuOpened(int id, Menu menu) {
837 if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
838 MenuDoubleTabUtil.recordMenuOpen();
839 }
840 return super.onMenuOpened(id, menu);
841 }
842
843 protected void showQrCode() {
844 showQrCode(getShareableUri());
845 }
846
847 protected void showQrCode(final String uri) {
848 if (uri == null || uri.isEmpty()) {
849 return;
850 }
851 Point size = new Point();
852 getWindowManager().getDefaultDisplay().getSize(size);
853 final int width = (size.x < size.y ? size.x : size.y);
854 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
855 ImageView view = new ImageView(this);
856 view.setBackgroundColor(Color.WHITE);
857 view.setImageBitmap(bitmap);
858 AlertDialog.Builder builder = new AlertDialog.Builder(this);
859 builder.setView(view);
860 builder.create().show();
861 }
862
863 protected Account extractAccount(Intent intent) {
864 final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
865 try {
866 return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
867 } catch (IllegalArgumentException e) {
868 return null;
869 }
870 }
871
872 public AvatarService avatarService() {
873 return xmppConnectionService.getAvatarService();
874 }
875
876 public void loadBitmap(Message message, ImageView imageView) {
877 Bitmap bm;
878 try {
879 bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
880 } catch (IOException e) {
881 bm = null;
882 }
883 if (bm != null) {
884 cancelPotentialWork(message, imageView);
885 imageView.setImageBitmap(bm);
886 imageView.setBackgroundColor(0x00000000);
887 } else {
888 if (cancelPotentialWork(message, imageView)) {
889 imageView.setBackgroundColor(0xff333333);
890 imageView.setImageDrawable(null);
891 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
892 final AsyncDrawable asyncDrawable = new AsyncDrawable(
893 getResources(), null, task);
894 imageView.setImageDrawable(asyncDrawable);
895 try {
896 task.execute(message);
897 } catch (final RejectedExecutionException ignored) {
898 ignored.printStackTrace();
899 }
900 }
901 }
902 }
903
904 protected interface OnValueEdited {
905 String onValueEdited(String value);
906 }
907
908 public static class ConferenceInvite {
909 private String uuid;
910 private final List<Jid> jids = new ArrayList<>();
911
912 public static ConferenceInvite parse(Intent data) {
913 ConferenceInvite invite = new ConferenceInvite();
914 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
915 if (invite.uuid == null) {
916 return null;
917 }
918 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
919 return invite;
920 }
921
922 public boolean execute(XmppActivity activity) {
923 XmppConnectionService service = activity.xmppConnectionService;
924 Conversation conversation = service.findConversationByUuid(this.uuid);
925 if (conversation == null) {
926 return false;
927 }
928 if (conversation.getMode() == Conversation.MODE_MULTI) {
929 for (Jid jid : jids) {
930 service.invite(conversation, jid);
931 }
932 return false;
933 } else {
934 jids.add(conversation.getJid().asBareJid());
935 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
936 }
937 }
938 }
939
940 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
941 private final WeakReference<ImageView> imageViewReference;
942 private Message message = null;
943
944 private BitmapWorkerTask(ImageView imageView) {
945 this.imageViewReference = new WeakReference<>(imageView);
946 }
947
948 @Override
949 protected Bitmap doInBackground(Message... params) {
950 if (isCancelled()) {
951 return null;
952 }
953 message = params[0];
954 try {
955 final XmppActivity activity = find(imageViewReference);
956 if (activity != null && activity.xmppConnectionService != null) {
957 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
958 } else {
959 return null;
960 }
961 } catch (IOException e) {
962 return null;
963 }
964 }
965
966 @Override
967 protected void onPostExecute(final Bitmap bitmap) {
968 if (!isCancelled()) {
969 final ImageView imageView = imageViewReference.get();
970 if (imageView != null) {
971 imageView.setImageBitmap(bitmap);
972 imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
973 }
974 }
975 }
976 }
977
978 private static class AsyncDrawable extends BitmapDrawable {
979 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
980
981 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
982 super(res, bitmap);
983 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
984 }
985
986 private BitmapWorkerTask getBitmapWorkerTask() {
987 return bitmapWorkerTaskReference.get();
988 }
989 }
990
991 public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
992 final View view = viewWeakReference.get();
993 return view == null ? null : find(view);
994 }
995
996 public static XmppActivity find(@NonNull final View view) {
997 Context context = view.getContext();
998 while (context instanceof ContextWrapper) {
999 if (context instanceof XmppActivity) {
1000 return (XmppActivity) context;
1001 }
1002 context = ((ContextWrapper) context).getBaseContext();
1003 }
1004 return null;
1005 }
1006}