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.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.support.annotation.BoolRes;
38import android.support.annotation.StringRes;
39import android.support.v4.content.ContextCompat;
40import android.support.v7.app.AlertDialog;
41import android.support.v7.app.AlertDialog.Builder;
42import android.support.v7.app.AppCompatDelegate;
43import android.text.InputType;
44import android.util.DisplayMetrics;
45import android.util.Log;
46import android.view.Menu;
47import android.view.MenuItem;
48import android.view.View;
49import android.widget.EditText;
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;
58import java.util.concurrent.atomic.AtomicBoolean;
59
60import eu.siacs.conversations.Config;
61import eu.siacs.conversations.R;
62import eu.siacs.conversations.crypto.PgpEngine;
63import eu.siacs.conversations.databinding.DialogQuickeditBinding;
64import eu.siacs.conversations.entities.Account;
65import eu.siacs.conversations.entities.Contact;
66import eu.siacs.conversations.entities.Conversation;
67import eu.siacs.conversations.entities.Message;
68import eu.siacs.conversations.entities.Presences;
69import eu.siacs.conversations.services.AvatarService;
70import eu.siacs.conversations.services.BarcodeProvider;
71import eu.siacs.conversations.services.XmppConnectionService;
72import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
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.ExceptionHelper;
77import eu.siacs.conversations.utils.ThemeHelper;
78import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
79import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
80import rocks.xmpp.addr.Jid;
81
82public abstract class XmppActivity extends ActionBarActivity {
83
84 public static final String EXTRA_ACCOUNT = "account";
85 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
86 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
87 protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
88 protected static final int REQUEST_BATTERY_OP = 0x49ff;
89 public XmppConnectionService xmppConnectionService;
90 public boolean xmppConnectionServiceBound = false;
91
92 protected int mColorRed;
93
94 protected static final String FRAGMENT_TAG_DIALOG = "dialog";
95
96 private boolean isCameraFeatureAvailable = false;
97
98 protected int mTheme;
99 protected boolean mUsingEnterKey = false;
100 protected Toast mToast;
101 public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
102 protected ConferenceInvite mPendingConferenceInvite = null;
103 protected ServiceConnection mConnection = new ServiceConnection() {
104
105 @Override
106 public void onServiceConnected(ComponentName className, IBinder service) {
107 XmppConnectionBinder binder = (XmppConnectionBinder) service;
108 xmppConnectionService = binder.getService();
109 xmppConnectionServiceBound = true;
110 registerListeners();
111 onBackendConnected();
112 }
113
114 @Override
115 public void onServiceDisconnected(ComponentName arg0) {
116 xmppConnectionServiceBound = false;
117 }
118 };
119 private DisplayMetrics metrics;
120 private long mLastUiRefresh = 0;
121 private Handler mRefreshUiHandler = new Handler();
122 private Runnable mRefreshUiRunnable = () -> {
123 mLastUiRefresh = SystemClock.elapsedRealtime();
124 refreshUiReal();
125 };
126 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
127 @Override
128 public void success(final Conversation conversation) {
129 runOnUiThread(() -> {
130 switchToConversation(conversation);
131 hideToast();
132 });
133 }
134
135 @Override
136 public void error(final int errorCode, Conversation object) {
137 runOnUiThread(() -> replaceToast(getString(errorCode)));
138 }
139
140 @Override
141 public void userInputRequried(PendingIntent pi, Conversation object) {
142
143 }
144 };
145 public boolean mSkipBackgroundBinding = false;
146
147 public static boolean cancelPotentialWork(Message message, ImageView imageView) {
148 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
149
150 if (bitmapWorkerTask != null) {
151 final Message oldMessage = bitmapWorkerTask.message;
152 if (oldMessage == null || message != oldMessage) {
153 bitmapWorkerTask.cancel(true);
154 } else {
155 return false;
156 }
157 }
158 return true;
159 }
160
161 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
162 if (imageView != null) {
163 final Drawable drawable = imageView.getDrawable();
164 if (drawable instanceof AsyncDrawable) {
165 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
166 return asyncDrawable.getBitmapWorkerTask();
167 }
168 }
169 return null;
170 }
171
172 protected void hideToast() {
173 if (mToast != null) {
174 mToast.cancel();
175 }
176 }
177
178 protected void replaceToast(String msg) {
179 replaceToast(msg, true);
180 }
181
182 protected void replaceToast(String msg, boolean showlong) {
183 hideToast();
184 mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
185 mToast.show();
186 }
187
188 protected final void refreshUi() {
189 final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
190 if (diff > Config.REFRESH_UI_INTERVAL) {
191 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
192 runOnUiThread(mRefreshUiRunnable);
193 } else {
194 final long next = Config.REFRESH_UI_INTERVAL - diff;
195 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
196 mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
197 }
198 }
199
200 abstract protected void refreshUiReal();
201
202 @Override
203 protected void onStart() {
204 super.onStart();
205 if (!xmppConnectionServiceBound) {
206 if (this.mSkipBackgroundBinding) {
207 Log.d(Config.LOGTAG,"skipping background binding");
208 } else {
209 connectToBackend();
210 }
211 } else {
212 this.registerListeners();
213 this.onBackendConnected();
214 }
215 }
216
217 public void connectToBackend() {
218 Intent intent = new Intent(this, XmppConnectionService.class);
219 intent.setAction("ui");
220 startService(intent);
221 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
222 }
223
224 @Override
225 protected void onStop() {
226 super.onStop();
227 if (xmppConnectionServiceBound) {
228 this.unregisterListeners();
229 unbindService(mConnection);
230 xmppConnectionServiceBound = false;
231 }
232 }
233
234
235 public boolean hasPgp() {
236 return xmppConnectionService.getPgpEngine() != null;
237 }
238
239 public void showInstallPgpDialog() {
240 Builder builder = new AlertDialog.Builder(this);
241 builder.setTitle(getString(R.string.openkeychain_required));
242 builder.setIconAttribute(android.R.attr.alertDialogIcon);
243 builder.setMessage(getText(R.string.openkeychain_required_long));
244 builder.setNegativeButton(getString(R.string.cancel), null);
245 builder.setNeutralButton(getString(R.string.restart),
246 (dialog, which) -> {
247 if (xmppConnectionServiceBound) {
248 unbindService(mConnection);
249 xmppConnectionServiceBound = false;
250 }
251 stopService(new Intent(XmppActivity.this,
252 XmppConnectionService.class));
253 finish();
254 });
255 builder.setPositiveButton(getString(R.string.install),
256 (dialog, which) -> {
257 Uri uri = Uri
258 .parse("market://details?id=org.sufficientlysecure.keychain");
259 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
260 uri);
261 PackageManager manager = getApplicationContext()
262 .getPackageManager();
263 List<ResolveInfo> infos = manager
264 .queryIntentActivities(marketIntent, 0);
265 if (infos.size() > 0) {
266 startActivity(marketIntent);
267 } else {
268 uri = Uri.parse("http://www.openkeychain.org/");
269 Intent browserIntent = new Intent(
270 Intent.ACTION_VIEW, uri);
271 startActivity(browserIntent);
272 }
273 finish();
274 });
275 builder.create().show();
276 }
277
278 abstract void onBackendConnected();
279
280 protected void registerListeners() {
281 if (this instanceof XmppConnectionService.OnConversationUpdate) {
282 this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
283 }
284 if (this instanceof XmppConnectionService.OnAccountUpdate) {
285 this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
286 }
287 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
288 this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
289 }
290 if (this instanceof XmppConnectionService.OnRosterUpdate) {
291 this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
292 }
293 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
294 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
295 }
296 if (this instanceof OnUpdateBlocklist) {
297 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
298 }
299 if (this instanceof XmppConnectionService.OnShowErrorToast) {
300 this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
301 }
302 if (this instanceof OnKeyStatusUpdated) {
303 this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
304 }
305 }
306
307 protected void unregisterListeners() {
308 if (this instanceof XmppConnectionService.OnConversationUpdate) {
309 this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
310 }
311 if (this instanceof XmppConnectionService.OnAccountUpdate) {
312 this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
313 }
314 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
315 this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
316 }
317 if (this instanceof XmppConnectionService.OnRosterUpdate) {
318 this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
319 }
320 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
321 this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
322 }
323 if (this instanceof OnUpdateBlocklist) {
324 this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
325 }
326 if (this instanceof XmppConnectionService.OnShowErrorToast) {
327 this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
328 }
329 if (this instanceof OnKeyStatusUpdated) {
330 this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
331 }
332 }
333
334 @Override
335 public boolean onOptionsItemSelected(final MenuItem item) {
336 switch (item.getItemId()) {
337 case R.id.action_settings:
338 startActivity(new Intent(this, SettingsActivity.class));
339 break;
340 case R.id.action_accounts:
341 startActivity(new Intent(this, ManageAccountActivity.class));
342 break;
343 case android.R.id.home:
344 finish();
345 break;
346 case R.id.action_show_qr_code:
347 showQrCode();
348 break;
349 }
350 return super.onOptionsItemSelected(item);
351 }
352
353 public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
354 final Contact contact = conversation.getContact();
355 if (!contact.showInRoster()) {
356 showAddToRosterDialog(conversation.getContact());
357 } else {
358 final Presences presences = contact.getPresences();
359 if (presences.size() == 0) {
360 if (!contact.getOption(Contact.Options.TO)
361 && !contact.getOption(Contact.Options.ASKING)
362 && contact.getAccount().getStatus() == Account.State.ONLINE) {
363 showAskForPresenceDialog(contact);
364 } else if (!contact.getOption(Contact.Options.TO)
365 || !contact.getOption(Contact.Options.FROM)) {
366 PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
367 } else {
368 conversation.setNextCounterpart(null);
369 listener.onPresenceSelected();
370 }
371 } else if (presences.size() == 1) {
372 String presence = presences.toResourceArray()[0];
373 try {
374 conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence));
375 } catch (IllegalArgumentException e) {
376 conversation.setNextCounterpart(null);
377 }
378 listener.onPresenceSelected();
379 } else {
380 PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
381 }
382 }
383 }
384
385 @Override
386 protected void onCreate(Bundle savedInstanceState) {
387 super.onCreate(savedInstanceState);
388 metrics = getResources().getDisplayMetrics();
389 ExceptionHelper.init(getApplicationContext());
390 this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
391
392 mColorRed = ContextCompat.getColor(this, R.color.red800);
393
394 this.mTheme = findTheme();
395 setTheme(this.mTheme);
396
397 this.mUsingEnterKey = usingEnterKey();
398 }
399
400 protected boolean isCameraFeatureAvailable() {
401 return this.isCameraFeatureAvailable;
402 }
403
404 public boolean isDarkTheme() {
405 return ThemeHelper.isDark(mTheme);
406 }
407
408 public int getThemeResource(int r_attr_name, int r_drawable_def) {
409 int[] attrs = {r_attr_name};
410 TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
411
412 int res = ta.getResourceId(0, r_drawable_def);
413 ta.recycle();
414
415 return res;
416 }
417
418 protected boolean isOptimizingBattery() {
419 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
420 final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
421 return pm != null
422 && !pm.isIgnoringBatteryOptimizations(getPackageName());
423 } else {
424 return false;
425 }
426 }
427
428 protected boolean isAffectedByDataSaver() {
429 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
430 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
431 return cm != null
432 && cm.isActiveNetworkMetered()
433 && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
434 } else {
435 return false;
436 }
437 }
438
439 protected boolean usingEnterKey() {
440 return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
441 }
442
443 protected SharedPreferences getPreferences() {
444 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
445 }
446
447 protected boolean getBooleanPreference(String name, @BoolRes int res) {
448 return getPreferences().getBoolean(name, getResources().getBoolean(res));
449 }
450
451 public void switchToConversation(Conversation conversation) {
452 switchToConversation(conversation, null, false);
453 }
454
455 public void switchToConversationAndQuote(Conversation conversation, String text) {
456 switchToConversation(conversation, text, true, null, false, false);
457 }
458
459 public void switchToConversation(Conversation conversation, String text, boolean newTask) {
460 switchToConversation(conversation, text, false, null, false, newTask);
461 }
462
463 public void highlightInMuc(Conversation conversation, String nick) {
464 switchToConversation(conversation, null, false, nick, false, false);
465 }
466
467 public void privateMsgInMuc(Conversation conversation, String nick) {
468 switchToConversation(conversation, null, false, nick, true, false);
469 }
470
471 private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean newTask) {
472 Intent intent = new Intent(this, ConversationsActivity.class);
473 intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
474 intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
475 if (text != null) {
476 intent.putExtra(ConversationsActivity.EXTRA_TEXT, text);
477 if (asQuote) {
478 intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, asQuote);
479 }
480 }
481 if (nick != null) {
482 intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
483 intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
484 }
485 if (newTask) {
486 intent.setFlags(intent.getFlags()
487 | Intent.FLAG_ACTIVITY_NEW_TASK
488 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
489 } else {
490 intent.setFlags(intent.getFlags()
491 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
492 }
493 startActivity(intent);
494 finish();
495 }
496
497 public void switchToContactDetails(Contact contact) {
498 switchToContactDetails(contact, null);
499 }
500
501 public void switchToContactDetails(Contact contact, String messageFingerprint) {
502 Intent intent = new Intent(this, ContactDetailsActivity.class);
503 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
504 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString());
505 intent.putExtra("contact", contact.getJid().toString());
506 intent.putExtra("fingerprint", messageFingerprint);
507 startActivity(intent);
508 }
509
510 public void switchToAccount(Account account, String fingerprint) {
511 switchToAccount(account, false, fingerprint);
512 }
513
514 public void switchToAccount(Account account) {
515 switchToAccount(account, false, null);
516 }
517
518 public void switchToAccount(Account account, boolean init, String fingerprint) {
519 Intent intent = new Intent(this, EditAccountActivity.class);
520 intent.putExtra("jid", account.getJid().asBareJid().toString());
521 intent.putExtra("init", init);
522 if (init) {
523 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
524 }
525 if (fingerprint != null) {
526 intent.putExtra("fingerprint", fingerprint);
527 }
528 startActivity(intent);
529 if (init) {
530 overridePendingTransition(0, 0);
531 }
532 }
533
534 protected void delegateUriPermissionsToService(Uri uri) {
535 Intent intent = new Intent(this, XmppConnectionService.class);
536 intent.setAction(Intent.ACTION_SEND);
537 intent.setData(uri);
538 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
539 try {
540 startService(intent);
541 } catch (Exception e) {
542 Log.e(Config.LOGTAG,"unable to delegate uri permission",e);
543 }
544 }
545
546 protected void inviteToConversation(Conversation conversation) {
547 startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION);
548 }
549
550 protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
551 if (account.getPgpId() == 0) {
552 choosePgpSignId(account);
553 } else {
554 String status = null;
555 if (manuallyChangePresence()) {
556 status = account.getPresenceStatusMessage();
557 }
558 if (status == null) {
559 status = "";
560 }
561 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
562
563 @Override
564 public void userInputRequried(PendingIntent pi, String signature) {
565 try {
566 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
567 } catch (final SendIntentException ignored) {
568 }
569 }
570
571 @Override
572 public void success(String signature) {
573 account.setPgpSignature(signature);
574 xmppConnectionService.databaseBackend.updateAccount(account);
575 xmppConnectionService.sendPresence(account);
576 if (conversation != null) {
577 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
578 xmppConnectionService.updateConversation(conversation);
579 refreshUi();
580 }
581 if (onSuccess != null) {
582 runOnUiThread(onSuccess);
583 }
584 }
585
586 @Override
587 public void error(int error, String signature) {
588 if (error == 0) {
589 account.setPgpSignId(0);
590 account.unsetPgpSignature();
591 xmppConnectionService.databaseBackend.updateAccount(account);
592 choosePgpSignId(account);
593 } else {
594 displayErrorDialog(error);
595 }
596 }
597 });
598 }
599 }
600
601 protected boolean noAccountUsesPgp() {
602 if (!hasPgp()) {
603 return true;
604 }
605 for (Account account : xmppConnectionService.getAccounts()) {
606 if (account.getPgpId() != 0) {
607 return false;
608 }
609 }
610 return true;
611 }
612
613 @SuppressWarnings("deprecation")
614 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
615 protected void setListItemBackgroundOnView(View view) {
616 int sdk = android.os.Build.VERSION.SDK_INT;
617 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
618 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
619 } else {
620 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
621 }
622 }
623
624 protected void choosePgpSignId(Account account) {
625 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
626 @Override
627 public void success(Account account1) {
628 }
629
630 @Override
631 public void error(int errorCode, Account object) {
632
633 }
634
635 @Override
636 public void userInputRequried(PendingIntent pi, Account object) {
637 try {
638 startIntentSenderForResult(pi.getIntentSender(),
639 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
640 } catch (final SendIntentException ignored) {
641 }
642 }
643 });
644 }
645
646 protected void displayErrorDialog(final int errorCode) {
647 runOnUiThread(() -> {
648 Builder builder = new Builder(XmppActivity.this);
649 builder.setIconAttribute(android.R.attr.alertDialogIcon);
650 builder.setTitle(getString(R.string.error));
651 builder.setMessage(errorCode);
652 builder.setNeutralButton(R.string.accept, null);
653 builder.create().show();
654 });
655
656 }
657
658 protected void showAddToRosterDialog(final Contact contact) {
659 AlertDialog.Builder builder = new AlertDialog.Builder(this);
660 builder.setTitle(contact.getJid().toString());
661 builder.setMessage(getString(R.string.not_in_roster));
662 builder.setNegativeButton(getString(R.string.cancel), null);
663 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
664 builder.create().show();
665 }
666
667 private void showAskForPresenceDialog(final Contact contact) {
668 AlertDialog.Builder builder = new AlertDialog.Builder(this);
669 builder.setTitle(contact.getJid().toString());
670 builder.setMessage(R.string.request_presence_updates);
671 builder.setNegativeButton(R.string.cancel, null);
672 builder.setPositiveButton(R.string.request_now,
673 (dialog, which) -> {
674 if (xmppConnectionServiceBound) {
675 xmppConnectionService.sendPresencePacket(contact
676 .getAccount(), xmppConnectionService
677 .getPresenceGenerator()
678 .requestPresenceUpdatesFrom(contact));
679 }
680 });
681 builder.create().show();
682 }
683
684 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
685 quickEdit(previousValue, callback, hint, false, false);
686 }
687
688 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
689 quickEdit(previousValue, callback, hint, false, permitEmpty);
690 }
691
692 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
693 quickEdit(previousValue, callback, R.string.password, true, false);
694 }
695
696 @SuppressLint("InflateParams")
697 private void quickEdit(final String previousValue,
698 final OnValueEdited callback,
699 final @StringRes int hint,
700 boolean password,
701 boolean permitEmpty) {
702 AlertDialog.Builder builder = new AlertDialog.Builder(this);
703 DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false);
704 if (password) {
705 binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
706 }
707 builder.setPositiveButton(R.string.accept, null);
708 if (hint != 0) {
709 binding.inputLayout.setHint(getString(hint));
710 }
711 binding.inputEditText.requestFocus();
712 if (previousValue != null) {
713 binding.inputEditText.getText().append(previousValue);
714 }
715 builder.setView(binding.getRoot());
716 builder.setNegativeButton(R.string.cancel, null);
717 final AlertDialog dialog = builder.create();
718 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
719 dialog.show();
720 View.OnClickListener clickListener = v -> {
721 String value = binding.inputEditText.getText().toString();
722 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
723 String error = callback.onValueEdited(value);
724 if (error != null) {
725 binding.inputLayout.setError(error);
726 return;
727 }
728 }
729 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
730 dialog.dismiss();
731 };
732 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
733 dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
734 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
735 dialog.dismiss();
736 }));
737 dialog.setOnDismissListener(dialog1 -> {
738 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
739 });
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 getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, 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 (IOException 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(ChooseContactActivity.EXTRA_CONVERSATION);
925 if (invite.uuid == null) {
926 return null;
927 }
928 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
929 return invite;
930 }
931
932 public boolean execute(XmppActivity activity) {
933 XmppConnectionService service = activity.xmppConnectionService;
934 Conversation conversation = service.findConversationByUuid(this.uuid);
935 if (conversation == null) {
936 return false;
937 }
938 if (conversation.getMode() == Conversation.MODE_MULTI) {
939 for (Jid jid : jids) {
940 service.invite(conversation, jid);
941 }
942 return false;
943 } else {
944 jids.add(conversation.getJid().asBareJid());
945 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
946 }
947 }
948 }
949
950 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
951 private final WeakReference<ImageView> imageViewReference;
952 private final WeakReference<XmppActivity> activity;
953 private Message message = null;
954
955 private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
956 this.activity = new WeakReference<>(activity);
957 this.imageViewReference = new WeakReference<>(imageView);
958 }
959
960 @Override
961 protected Bitmap doInBackground(Message... params) {
962 if (isCancelled()) {
963 return null;
964 }
965 message = params[0];
966 try {
967 XmppActivity activity = this.activity.get();
968 if (activity != null && activity.xmppConnectionService != null) {
969 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
970 } else {
971 return null;
972 }
973 } catch (IOException e) {
974 return null;
975 }
976 }
977
978 @Override
979 protected void onPostExecute(Bitmap bitmap) {
980 if (bitmap != null && !isCancelled()) {
981 final ImageView imageView = imageViewReference.get();
982 if (imageView != null) {
983 imageView.setImageBitmap(bitmap);
984 imageView.setBackgroundColor(0x00000000);
985 }
986 }
987 }
988 }
989
990 private static class AsyncDrawable extends BitmapDrawable {
991 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
992
993 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
994 super(res, bitmap);
995 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
996 }
997
998 private BitmapWorkerTask getBitmapWorkerTask() {
999 return bitmapWorkerTaskReference.get();
1000 }
1001 }
1002}