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);
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) {
460 switchToConversation(conversation, text, false, null, false, false);
461 }
462
463 public void switchToConversationDoNotAppend(Conversation conversation, String text) {
464 switchToConversation(conversation, text, false, null, false, true);
465 }
466
467 public void highlightInMuc(Conversation conversation, String nick) {
468 switchToConversation(conversation, null, false, nick, false, false);
469 }
470
471 public void privateMsgInMuc(Conversation conversation, String nick) {
472 switchToConversation(conversation, null, false, nick, true, false);
473 }
474
475 private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
476 Intent intent = new Intent(this, ConversationsActivity.class);
477 intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
478 intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
479 if (text != null) {
480 intent.putExtra(Intent.EXTRA_TEXT, text);
481 if (asQuote) {
482 intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
483 }
484 }
485 if (nick != null) {
486 intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
487 intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
488 }
489 if (doNotAppend) {
490 intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
491 }
492 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
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 @SuppressWarnings("deprecation")
602 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
603 protected void setListItemBackgroundOnView(View view) {
604 int sdk = android.os.Build.VERSION.SDK_INT;
605 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
606 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
607 } else {
608 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
609 }
610 }
611
612 protected void choosePgpSignId(Account account) {
613 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
614 @Override
615 public void success(Account account1) {
616 }
617
618 @Override
619 public void error(int errorCode, Account object) {
620
621 }
622
623 @Override
624 public void userInputRequried(PendingIntent pi, Account object) {
625 try {
626 startIntentSenderForResult(pi.getIntentSender(),
627 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
628 } catch (final SendIntentException ignored) {
629 }
630 }
631 });
632 }
633
634 protected void displayErrorDialog(final int errorCode) {
635 runOnUiThread(() -> {
636 Builder builder = new Builder(XmppActivity.this);
637 builder.setIconAttribute(android.R.attr.alertDialogIcon);
638 builder.setTitle(getString(R.string.error));
639 builder.setMessage(errorCode);
640 builder.setNeutralButton(R.string.accept, null);
641 builder.create().show();
642 });
643
644 }
645
646 protected void showAddToRosterDialog(final Contact contact) {
647 AlertDialog.Builder builder = new AlertDialog.Builder(this);
648 builder.setTitle(contact.getJid().toString());
649 builder.setMessage(getString(R.string.not_in_roster));
650 builder.setNegativeButton(getString(R.string.cancel), null);
651 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
652 builder.create().show();
653 }
654
655 private void showAskForPresenceDialog(final Contact contact) {
656 AlertDialog.Builder builder = new AlertDialog.Builder(this);
657 builder.setTitle(contact.getJid().toString());
658 builder.setMessage(R.string.request_presence_updates);
659 builder.setNegativeButton(R.string.cancel, null);
660 builder.setPositiveButton(R.string.request_now,
661 (dialog, which) -> {
662 if (xmppConnectionServiceBound) {
663 xmppConnectionService.sendPresencePacket(contact
664 .getAccount(), xmppConnectionService
665 .getPresenceGenerator()
666 .requestPresenceUpdatesFrom(contact));
667 }
668 });
669 builder.create().show();
670 }
671
672 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
673 quickEdit(previousValue, callback, hint, false, false);
674 }
675
676 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
677 quickEdit(previousValue, callback, hint, false, permitEmpty);
678 }
679
680 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
681 quickEdit(previousValue, callback, R.string.password, true, false);
682 }
683
684 @SuppressLint("InflateParams")
685 private void quickEdit(final String previousValue,
686 final OnValueEdited callback,
687 final @StringRes int hint,
688 boolean password,
689 boolean permitEmpty) {
690 AlertDialog.Builder builder = new AlertDialog.Builder(this);
691 DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false);
692 if (password) {
693 binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
694 }
695 builder.setPositiveButton(R.string.accept, null);
696 if (hint != 0) {
697 binding.inputLayout.setHint(getString(hint));
698 }
699 binding.inputEditText.requestFocus();
700 if (previousValue != null) {
701 binding.inputEditText.getText().append(previousValue);
702 }
703 builder.setView(binding.getRoot());
704 builder.setNegativeButton(R.string.cancel, null);
705 final AlertDialog dialog = builder.create();
706 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
707 dialog.show();
708 View.OnClickListener clickListener = v -> {
709 String value = binding.inputEditText.getText().toString();
710 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
711 String error = callback.onValueEdited(value);
712 if (error != null) {
713 binding.inputLayout.setError(error);
714 return;
715 }
716 }
717 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
718 dialog.dismiss();
719 };
720 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
721 dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
722 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
723 dialog.dismiss();
724 }));
725 dialog.setOnDismissListener(dialog1 -> {
726 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
727 });
728 }
729
730 protected boolean hasStoragePermission(int requestCode) {
731 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
732 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
733 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
734 return false;
735 } else {
736 return true;
737 }
738 } else {
739 return true;
740 }
741 }
742
743 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
744 super.onActivityResult(requestCode, resultCode, data);
745 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
746 mPendingConferenceInvite = ConferenceInvite.parse(data);
747 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
748 if (mPendingConferenceInvite.execute(this)) {
749 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
750 mToast.show();
751 }
752 mPendingConferenceInvite = null;
753 }
754 }
755 }
756
757 public int getWarningTextColor() {
758 return this.mColorRed;
759 }
760
761 public int getPixel(int dp) {
762 DisplayMetrics metrics = getResources().getDisplayMetrics();
763 return ((int) (dp * metrics.density));
764 }
765
766 public boolean copyTextToClipboard(String text, int labelResId) {
767 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
768 String label = getResources().getString(labelResId);
769 if (mClipBoardManager != null) {
770 ClipData mClipData = ClipData.newPlainText(label, text);
771 mClipBoardManager.setPrimaryClip(mClipData);
772 return true;
773 }
774 return false;
775 }
776
777 protected boolean neverCompressPictures() {
778 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
779 }
780
781 protected boolean manuallyChangePresence() {
782 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
783 }
784
785 protected String getShareableUri() {
786 return getShareableUri(false);
787 }
788
789 protected String getShareableUri(boolean http) {
790 return null;
791 }
792
793 protected void shareLink(boolean http) {
794 String uri = getShareableUri(http);
795 if (uri == null || uri.isEmpty()) {
796 return;
797 }
798 Intent intent = new Intent(Intent.ACTION_SEND);
799 intent.setType("text/plain");
800 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
801 try {
802 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
803 } catch (ActivityNotFoundException e) {
804 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
805 }
806 }
807
808 protected void launchOpenKeyChain(long keyId) {
809 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
810 try {
811 startIntentSenderForResult(
812 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
813 0, 0);
814 } catch (Throwable e) {
815 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
816 }
817 }
818
819 @Override
820 public void onResume() {
821 super.onResume();
822 }
823
824 protected int findTheme() {
825 return ThemeHelper.find(this);
826 }
827
828 @Override
829 public void onPause() {
830 super.onPause();
831 }
832
833 @Override
834 public boolean onMenuOpened(int id, Menu menu) {
835 if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
836 MenuDoubleTabUtil.recordMenuOpen();
837 }
838 return super.onMenuOpened(id, menu);
839 }
840
841 protected void showQrCode() {
842 showQrCode(getShareableUri());
843 }
844
845 protected void showQrCode(final String uri) {
846 if (uri == null || uri.isEmpty()) {
847 return;
848 }
849 Point size = new Point();
850 getWindowManager().getDefaultDisplay().getSize(size);
851 final int width = (size.x < size.y ? size.x : size.y);
852 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
853 ImageView view = new ImageView(this);
854 view.setBackgroundColor(Color.WHITE);
855 view.setImageBitmap(bitmap);
856 AlertDialog.Builder builder = new AlertDialog.Builder(this);
857 builder.setView(view);
858 builder.create().show();
859 }
860
861 protected Account extractAccount(Intent intent) {
862 String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
863 try {
864 return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
865 } catch (IllegalArgumentException e) {
866 return null;
867 }
868 }
869
870 public AvatarService avatarService() {
871 return xmppConnectionService.getAvatarService();
872 }
873
874 public void loadBitmap(Message message, ImageView imageView) {
875 Bitmap bm;
876 try {
877 bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
878 } catch (IOException e) {
879 bm = null;
880 }
881 if (bm != null) {
882 cancelPotentialWork(message, imageView);
883 imageView.setImageBitmap(bm);
884 imageView.setBackgroundColor(0x00000000);
885 } else {
886 if (cancelPotentialWork(message, imageView)) {
887 imageView.setBackgroundColor(0xff333333);
888 imageView.setImageDrawable(null);
889 final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
890 final AsyncDrawable asyncDrawable = new AsyncDrawable(
891 getResources(), null, task);
892 imageView.setImageDrawable(asyncDrawable);
893 try {
894 task.execute(message);
895 } catch (final RejectedExecutionException ignored) {
896 ignored.printStackTrace();
897 }
898 }
899 }
900 }
901
902 protected interface OnValueEdited {
903 String onValueEdited(String value);
904 }
905
906 public static class ConferenceInvite {
907 private String uuid;
908 private List<Jid> jids = new ArrayList<>();
909
910 public static ConferenceInvite parse(Intent data) {
911 ConferenceInvite invite = new ConferenceInvite();
912 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
913 if (invite.uuid == null) {
914 return null;
915 }
916 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
917 return invite;
918 }
919
920 public boolean execute(XmppActivity activity) {
921 XmppConnectionService service = activity.xmppConnectionService;
922 Conversation conversation = service.findConversationByUuid(this.uuid);
923 if (conversation == null) {
924 return false;
925 }
926 if (conversation.getMode() == Conversation.MODE_MULTI) {
927 for (Jid jid : jids) {
928 service.invite(conversation, jid);
929 }
930 return false;
931 } else {
932 jids.add(conversation.getJid().asBareJid());
933 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
934 }
935 }
936 }
937
938 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
939 private final WeakReference<ImageView> imageViewReference;
940 private final WeakReference<XmppActivity> activity;
941 private Message message = null;
942
943 private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
944 this.activity = new WeakReference<>(activity);
945 this.imageViewReference = new WeakReference<>(imageView);
946 }
947
948 @Override
949 protected Bitmap doInBackground(Message... params) {
950 if (isCancelled()) {
951 return null;
952 }
953 message = params[0];
954 try {
955 XmppActivity activity = this.activity.get();
956 if (activity != null && activity.xmppConnectionService != null) {
957 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
958 } else {
959 return null;
960 }
961 } catch (IOException e) {
962 return null;
963 }
964 }
965
966 @Override
967 protected void onPostExecute(final Bitmap bitmap) {
968 if (!isCancelled()) {
969 final ImageView imageView = imageViewReference.get();
970 if (imageView != null) {
971 imageView.setImageBitmap(bitmap);
972 imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
973 }
974 }
975 }
976 }
977
978 private static class AsyncDrawable extends BitmapDrawable {
979 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
980
981 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
982 super(res, bitmap);
983 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
984 }
985
986 private BitmapWorkerTask getBitmapWorkerTask() {
987 return bitmapWorkerTaskReference.get();
988 }
989 }
990}