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