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.util.MenuDoubleTabUtil;
73import eu.siacs.conversations.ui.util.PresenceSelector;
74import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
75import eu.siacs.conversations.utils.AccountUtils;
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 try {
221 startService(intent);
222 } catch (IllegalStateException e) {
223 Log.w(Config.LOGTAG,"unable to start service from "+getClass().getSimpleName());
224 }
225 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
226 }
227
228 @Override
229 protected void onStop() {
230 super.onStop();
231 if (xmppConnectionServiceBound) {
232 this.unregisterListeners();
233 unbindService(mConnection);
234 xmppConnectionServiceBound = false;
235 }
236 }
237
238
239 public boolean hasPgp() {
240 return xmppConnectionService.getPgpEngine() != null;
241 }
242
243 public void showInstallPgpDialog() {
244 Builder builder = new AlertDialog.Builder(this);
245 builder.setTitle(getString(R.string.openkeychain_required));
246 builder.setIconAttribute(android.R.attr.alertDialogIcon);
247 builder.setMessage(getText(R.string.openkeychain_required_long));
248 builder.setNegativeButton(getString(R.string.cancel), null);
249 builder.setNeutralButton(getString(R.string.restart),
250 (dialog, which) -> {
251 if (xmppConnectionServiceBound) {
252 unbindService(mConnection);
253 xmppConnectionServiceBound = false;
254 }
255 stopService(new Intent(XmppActivity.this,
256 XmppConnectionService.class));
257 finish();
258 });
259 builder.setPositiveButton(getString(R.string.install),
260 (dialog, which) -> {
261 Uri uri = Uri
262 .parse("market://details?id=org.sufficientlysecure.keychain");
263 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
264 uri);
265 PackageManager manager = getApplicationContext()
266 .getPackageManager();
267 List<ResolveInfo> infos = manager
268 .queryIntentActivities(marketIntent, 0);
269 if (infos.size() > 0) {
270 startActivity(marketIntent);
271 } else {
272 uri = Uri.parse("http://www.openkeychain.org/");
273 Intent browserIntent = new Intent(
274 Intent.ACTION_VIEW, uri);
275 startActivity(browserIntent);
276 }
277 finish();
278 });
279 builder.create().show();
280 }
281
282 abstract void onBackendConnected();
283
284 protected void registerListeners() {
285 if (this instanceof XmppConnectionService.OnConversationUpdate) {
286 this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
287 }
288 if (this instanceof XmppConnectionService.OnAccountUpdate) {
289 this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
290 }
291 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
292 this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
293 }
294 if (this instanceof XmppConnectionService.OnRosterUpdate) {
295 this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
296 }
297 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
298 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
299 }
300 if (this instanceof OnUpdateBlocklist) {
301 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
302 }
303 if (this instanceof XmppConnectionService.OnShowErrorToast) {
304 this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
305 }
306 if (this instanceof OnKeyStatusUpdated) {
307 this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
308 }
309 }
310
311 protected void unregisterListeners() {
312 if (this instanceof XmppConnectionService.OnConversationUpdate) {
313 this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
314 }
315 if (this instanceof XmppConnectionService.OnAccountUpdate) {
316 this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
317 }
318 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
319 this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
320 }
321 if (this instanceof XmppConnectionService.OnRosterUpdate) {
322 this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
323 }
324 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
325 this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
326 }
327 if (this instanceof OnUpdateBlocklist) {
328 this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
329 }
330 if (this instanceof XmppConnectionService.OnShowErrorToast) {
331 this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
332 }
333 if (this instanceof OnKeyStatusUpdated) {
334 this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
335 }
336 }
337
338 @Override
339 public boolean onOptionsItemSelected(final MenuItem item) {
340 switch (item.getItemId()) {
341 case R.id.action_settings:
342 startActivity(new Intent(this, SettingsActivity.class));
343 break;
344 case R.id.action_accounts:
345 AccountUtils.launchManageAccounts(this);
346 break;
347 case R.id.action_account:
348 AccountUtils.launchManageAccount(this);
349 break;
350 case android.R.id.home:
351 finish();
352 break;
353 case R.id.action_show_qr_code:
354 showQrCode();
355 break;
356 }
357 return super.onOptionsItemSelected(item);
358 }
359
360 public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
361 final Contact contact = conversation.getContact();
362 if (!contact.showInRoster()) {
363 showAddToRosterDialog(conversation.getContact());
364 } else {
365 final Presences presences = contact.getPresences();
366 if (presences.size() == 0) {
367 if (!contact.getOption(Contact.Options.TO)
368 && !contact.getOption(Contact.Options.ASKING)
369 && contact.getAccount().getStatus() == Account.State.ONLINE) {
370 showAskForPresenceDialog(contact);
371 } else if (!contact.getOption(Contact.Options.TO)
372 || !contact.getOption(Contact.Options.FROM)) {
373 PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
374 } else {
375 conversation.setNextCounterpart(null);
376 listener.onPresenceSelected();
377 }
378 } else if (presences.size() == 1) {
379 String presence = presences.toResourceArray()[0];
380 try {
381 conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence));
382 } catch (IllegalArgumentException e) {
383 conversation.setNextCounterpart(null);
384 }
385 listener.onPresenceSelected();
386 } else {
387 PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
388 }
389 }
390 }
391
392 @Override
393 protected void onCreate(Bundle savedInstanceState) {
394 super.onCreate(savedInstanceState);
395 setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
396 metrics = getResources().getDisplayMetrics();
397 ExceptionHelper.init(getApplicationContext());
398 this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
399
400 mColorRed = ContextCompat.getColor(this, R.color.red800);
401
402 this.mTheme = findTheme();
403 setTheme(this.mTheme);
404
405 this.mUsingEnterKey = usingEnterKey();
406 }
407
408 protected boolean isCameraFeatureAvailable() {
409 return this.isCameraFeatureAvailable;
410 }
411
412 public boolean isDarkTheme() {
413 return ThemeHelper.isDark(mTheme);
414 }
415
416 public int getThemeResource(int r_attr_name, int r_drawable_def) {
417 int[] attrs = {r_attr_name};
418 TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
419
420 int res = ta.getResourceId(0, r_drawable_def);
421 ta.recycle();
422
423 return res;
424 }
425
426 protected boolean isOptimizingBattery() {
427 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
428 final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
429 return pm != null
430 && !pm.isIgnoringBatteryOptimizations(getPackageName());
431 } else {
432 return false;
433 }
434 }
435
436 protected boolean isAffectedByDataSaver() {
437 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
438 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
439 return cm != null
440 && cm.isActiveNetworkMetered()
441 && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
442 } else {
443 return false;
444 }
445 }
446
447 protected boolean usingEnterKey() {
448 return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
449 }
450
451 protected SharedPreferences getPreferences() {
452 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
453 }
454
455 protected boolean getBooleanPreference(String name, @BoolRes int res) {
456 return getPreferences().getBoolean(name, getResources().getBoolean(res));
457 }
458
459 public void switchToConversation(Conversation conversation) {
460 switchToConversation(conversation, null);
461 }
462
463 public void switchToConversationAndQuote(Conversation conversation, String text) {
464 switchToConversation(conversation, text, true, null, false, false);
465 }
466
467 public void switchToConversation(Conversation conversation, String text) {
468 switchToConversation(conversation, text, false, null, false, false);
469 }
470
471 public void switchToConversationDoNotAppend(Conversation conversation, String text) {
472 switchToConversation(conversation, text, false, null, false, true);
473 }
474
475 public void highlightInMuc(Conversation conversation, String nick) {
476 switchToConversation(conversation, null, false, nick, false, false);
477 }
478
479 public void privateMsgInMuc(Conversation conversation, String nick) {
480 switchToConversation(conversation, null, false, nick, true, false);
481 }
482
483 private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
484 Intent intent = new Intent(this, ConversationsActivity.class);
485 intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
486 intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
487 if (text != null) {
488 intent.putExtra(Intent.EXTRA_TEXT, text);
489 if (asQuote) {
490 intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
491 }
492 }
493 if (nick != null) {
494 intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
495 intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
496 }
497 if (doNotAppend) {
498 intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
499 }
500 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
501 startActivity(intent);
502 finish();
503 }
504
505 public void switchToContactDetails(Contact contact) {
506 switchToContactDetails(contact, null);
507 }
508
509 public void switchToContactDetails(Contact contact, String messageFingerprint) {
510 Intent intent = new Intent(this, ContactDetailsActivity.class);
511 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
512 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString());
513 intent.putExtra("contact", contact.getJid().toString());
514 intent.putExtra("fingerprint", messageFingerprint);
515 startActivity(intent);
516 }
517
518 public void switchToAccount(Account account, String fingerprint) {
519 switchToAccount(account, false, fingerprint);
520 }
521
522 public void switchToAccount(Account account) {
523 switchToAccount(account, false, null);
524 }
525
526 public void switchToAccount(Account account, boolean init, String fingerprint) {
527 Intent intent = new Intent(this, EditAccountActivity.class);
528 intent.putExtra("jid", account.getJid().asBareJid().toString());
529 intent.putExtra("init", init);
530 if (init) {
531 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
532 }
533 if (fingerprint != null) {
534 intent.putExtra("fingerprint", fingerprint);
535 }
536 startActivity(intent);
537 if (init) {
538 overridePendingTransition(0, 0);
539 }
540 }
541
542 protected void delegateUriPermissionsToService(Uri uri) {
543 Intent intent = new Intent(this, XmppConnectionService.class);
544 intent.setAction(Intent.ACTION_SEND);
545 intent.setData(uri);
546 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
547 try {
548 startService(intent);
549 } catch (Exception e) {
550 Log.e(Config.LOGTAG,"unable to delegate uri permission",e);
551 }
552 }
553
554 protected void inviteToConversation(Conversation conversation) {
555 startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION);
556 }
557
558 protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
559 if (account.getPgpId() == 0) {
560 choosePgpSignId(account);
561 } else {
562 String status = null;
563 if (manuallyChangePresence()) {
564 status = account.getPresenceStatusMessage();
565 }
566 if (status == null) {
567 status = "";
568 }
569 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
570
571 @Override
572 public void userInputRequried(PendingIntent pi, String signature) {
573 try {
574 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
575 } catch (final SendIntentException ignored) {
576 }
577 }
578
579 @Override
580 public void success(String signature) {
581 account.setPgpSignature(signature);
582 xmppConnectionService.databaseBackend.updateAccount(account);
583 xmppConnectionService.sendPresence(account);
584 if (conversation != null) {
585 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
586 xmppConnectionService.updateConversation(conversation);
587 refreshUi();
588 }
589 if (onSuccess != null) {
590 runOnUiThread(onSuccess);
591 }
592 }
593
594 @Override
595 public void error(int error, String signature) {
596 if (error == 0) {
597 account.setPgpSignId(0);
598 account.unsetPgpSignature();
599 xmppConnectionService.databaseBackend.updateAccount(account);
600 choosePgpSignId(account);
601 } else {
602 displayErrorDialog(error);
603 }
604 }
605 });
606 }
607 }
608
609 @SuppressWarnings("deprecation")
610 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
611 protected void setListItemBackgroundOnView(View view) {
612 int sdk = android.os.Build.VERSION.SDK_INT;
613 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
614 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
615 } else {
616 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
617 }
618 }
619
620 protected void choosePgpSignId(Account account) {
621 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
622 @Override
623 public void success(Account account1) {
624 }
625
626 @Override
627 public void error(int errorCode, Account object) {
628
629 }
630
631 @Override
632 public void userInputRequried(PendingIntent pi, Account object) {
633 try {
634 startIntentSenderForResult(pi.getIntentSender(),
635 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
636 } catch (final SendIntentException ignored) {
637 }
638 }
639 });
640 }
641
642 protected void displayErrorDialog(final int errorCode) {
643 runOnUiThread(() -> {
644 Builder builder = new Builder(XmppActivity.this);
645 builder.setIconAttribute(android.R.attr.alertDialogIcon);
646 builder.setTitle(getString(R.string.error));
647 builder.setMessage(errorCode);
648 builder.setNeutralButton(R.string.accept, null);
649 builder.create().show();
650 });
651
652 }
653
654 protected void showAddToRosterDialog(final Contact contact) {
655 AlertDialog.Builder builder = new AlertDialog.Builder(this);
656 builder.setTitle(contact.getJid().toString());
657 builder.setMessage(getString(R.string.not_in_roster));
658 builder.setNegativeButton(getString(R.string.cancel), null);
659 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
660 builder.create().show();
661 }
662
663 private void showAskForPresenceDialog(final Contact contact) {
664 AlertDialog.Builder builder = new AlertDialog.Builder(this);
665 builder.setTitle(contact.getJid().toString());
666 builder.setMessage(R.string.request_presence_updates);
667 builder.setNegativeButton(R.string.cancel, null);
668 builder.setPositiveButton(R.string.request_now,
669 (dialog, which) -> {
670 if (xmppConnectionServiceBound) {
671 xmppConnectionService.sendPresencePacket(contact
672 .getAccount(), xmppConnectionService
673 .getPresenceGenerator()
674 .requestPresenceUpdatesFrom(contact));
675 }
676 });
677 builder.create().show();
678 }
679
680 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
681 quickEdit(previousValue, callback, hint, false, false);
682 }
683
684 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
685 quickEdit(previousValue, callback, hint, false, permitEmpty);
686 }
687
688 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
689 quickEdit(previousValue, callback, R.string.password, true, false);
690 }
691
692 @SuppressLint("InflateParams")
693 private void quickEdit(final String previousValue,
694 final OnValueEdited callback,
695 final @StringRes int hint,
696 boolean password,
697 boolean permitEmpty) {
698 AlertDialog.Builder builder = new AlertDialog.Builder(this);
699 DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false);
700 if (password) {
701 binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
702 }
703 builder.setPositiveButton(R.string.accept, null);
704 if (hint != 0) {
705 binding.inputLayout.setHint(getString(hint));
706 }
707 binding.inputEditText.requestFocus();
708 if (previousValue != null) {
709 binding.inputEditText.getText().append(previousValue);
710 }
711 builder.setView(binding.getRoot());
712 builder.setNegativeButton(R.string.cancel, null);
713 final AlertDialog dialog = builder.create();
714 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
715 dialog.show();
716 View.OnClickListener clickListener = v -> {
717 String value = binding.inputEditText.getText().toString();
718 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
719 String error = callback.onValueEdited(value);
720 if (error != null) {
721 binding.inputLayout.setError(error);
722 return;
723 }
724 }
725 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
726 dialog.dismiss();
727 };
728 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
729 dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
730 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
731 dialog.dismiss();
732 }));
733 dialog.setCanceledOnTouchOutside(false);
734 dialog.setOnDismissListener(dialog1 -> {
735 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
736 });
737 }
738
739 protected boolean hasStoragePermission(int requestCode) {
740 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
741 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
742 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
743 return false;
744 } else {
745 return true;
746 }
747 } else {
748 return true;
749 }
750 }
751
752 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
753 super.onActivityResult(requestCode, resultCode, data);
754 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
755 mPendingConferenceInvite = ConferenceInvite.parse(data);
756 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
757 if (mPendingConferenceInvite.execute(this)) {
758 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
759 mToast.show();
760 }
761 mPendingConferenceInvite = null;
762 }
763 }
764 }
765
766 public int getWarningTextColor() {
767 return this.mColorRed;
768 }
769
770 public int getPixel(int dp) {
771 DisplayMetrics metrics = getResources().getDisplayMetrics();
772 return ((int) (dp * metrics.density));
773 }
774
775 public boolean copyTextToClipboard(String text, int labelResId) {
776 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
777 String label = getResources().getString(labelResId);
778 if (mClipBoardManager != null) {
779 ClipData mClipData = ClipData.newPlainText(label, text);
780 mClipBoardManager.setPrimaryClip(mClipData);
781 return true;
782 }
783 return false;
784 }
785
786 protected boolean manuallyChangePresence() {
787 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
788 }
789
790 protected String getShareableUri() {
791 return getShareableUri(false);
792 }
793
794 protected String getShareableUri(boolean http) {
795 return null;
796 }
797
798 protected void shareLink(boolean http) {
799 String uri = getShareableUri(http);
800 if (uri == null || uri.isEmpty()) {
801 return;
802 }
803 Intent intent = new Intent(Intent.ACTION_SEND);
804 intent.setType("text/plain");
805 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
806 try {
807 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
808 } catch (ActivityNotFoundException e) {
809 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
810 }
811 }
812
813 protected void launchOpenKeyChain(long keyId) {
814 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
815 try {
816 startIntentSenderForResult(
817 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
818 0, 0);
819 } catch (Throwable e) {
820 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
821 }
822 }
823
824 @Override
825 public void onResume() {
826 super.onResume();
827 }
828
829 protected int findTheme() {
830 return ThemeHelper.find(this);
831 }
832
833 @Override
834 public void onPause() {
835 super.onPause();
836 }
837
838 @Override
839 public boolean onMenuOpened(int id, Menu menu) {
840 if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
841 MenuDoubleTabUtil.recordMenuOpen();
842 }
843 return super.onMenuOpened(id, menu);
844 }
845
846 protected void showQrCode() {
847 showQrCode(getShareableUri());
848 }
849
850 protected void showQrCode(final String uri) {
851 if (uri == null || uri.isEmpty()) {
852 return;
853 }
854 Point size = new Point();
855 getWindowManager().getDefaultDisplay().getSize(size);
856 final int width = (size.x < size.y ? size.x : size.y);
857 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
858 ImageView view = new ImageView(this);
859 view.setBackgroundColor(Color.WHITE);
860 view.setImageBitmap(bitmap);
861 AlertDialog.Builder builder = new AlertDialog.Builder(this);
862 builder.setView(view);
863 builder.create().show();
864 }
865
866 protected Account extractAccount(Intent intent) {
867 String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
868 try {
869 return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
870 } catch (IllegalArgumentException e) {
871 return null;
872 }
873 }
874
875 public AvatarService avatarService() {
876 return xmppConnectionService.getAvatarService();
877 }
878
879 public void loadBitmap(Message message, ImageView imageView) {
880 Bitmap bm;
881 try {
882 bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
883 } catch (IOException e) {
884 bm = null;
885 }
886 if (bm != null) {
887 cancelPotentialWork(message, imageView);
888 imageView.setImageBitmap(bm);
889 imageView.setBackgroundColor(0x00000000);
890 } else {
891 if (cancelPotentialWork(message, imageView)) {
892 imageView.setBackgroundColor(0xff333333);
893 imageView.setImageDrawable(null);
894 final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
895 final AsyncDrawable asyncDrawable = new AsyncDrawable(
896 getResources(), null, task);
897 imageView.setImageDrawable(asyncDrawable);
898 try {
899 task.execute(message);
900 } catch (final RejectedExecutionException ignored) {
901 ignored.printStackTrace();
902 }
903 }
904 }
905 }
906
907 protected interface OnValueEdited {
908 String onValueEdited(String value);
909 }
910
911 public static class ConferenceInvite {
912 private String uuid;
913 private List<Jid> jids = new ArrayList<>();
914
915 public static ConferenceInvite parse(Intent data) {
916 ConferenceInvite invite = new ConferenceInvite();
917 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
918 if (invite.uuid == null) {
919 return null;
920 }
921 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
922 return invite;
923 }
924
925 public boolean execute(XmppActivity activity) {
926 XmppConnectionService service = activity.xmppConnectionService;
927 Conversation conversation = service.findConversationByUuid(this.uuid);
928 if (conversation == null) {
929 return false;
930 }
931 if (conversation.getMode() == Conversation.MODE_MULTI) {
932 for (Jid jid : jids) {
933 service.invite(conversation, jid);
934 }
935 return false;
936 } else {
937 jids.add(conversation.getJid().asBareJid());
938 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
939 }
940 }
941 }
942
943 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
944 private final WeakReference<ImageView> imageViewReference;
945 private final WeakReference<XmppActivity> activity;
946 private Message message = null;
947
948 private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
949 this.activity = new WeakReference<>(activity);
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 XmppActivity activity = this.activity.get();
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}