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