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